package com.yaodian100.mall.mobilexml;

import java.io.StringWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.geronimo.mail.util.Base64;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.json.JSONUtil;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.opensymphony.xwork2.ActionContext;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.common.utils.HtmlRegexUtil;
import com.yaodian100.core.common.utils.JspUtil;
import com.yaodian100.core.common.utils.PasswordUtils;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.mail.entity.Mail;
import com.yaodian100.core.mail.service.MailService;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.entity.Option;
import com.yaodian100.crm.cs.service.CsService;
import com.yaodian100.ec.announcement.entity.Announcement;
import com.yaodian100.ec.announcement.service.AnnouncementService;
import com.yaodian100.ec.campaign.entity.CampaignProduct;
import com.yaodian100.ec.category.entity.Category;
import com.yaodian100.ec.category.service.CategoryService;
import com.yaodian100.ec.channel.service.ChannelService;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.coupon.entity.Coupon;
import com.yaodian100.ec.coupon.entity.CouponItem;
import com.yaodian100.ec.coupon.service.CouponService;
import com.yaodian100.ec.delivery.entity.DeliveryRule;
import com.yaodian100.ec.delivery.entity.ViewDeliveryRule;
import com.yaodian100.ec.delivery.service.DeliveryRuleService;
import com.yaodian100.ec.generate.service.GenerateOrderService;
import com.yaodian100.ec.givebonus.entity.BonusSetting;
import com.yaodian100.ec.givebonus.service.BonusSettingService;
import com.yaodian100.ec.image.entity.Image;
import com.yaodian100.ec.image.service.ImageService;
import com.yaodian100.ec.member.entity.AddressBook;
import com.yaodian100.ec.member.entity.Balance;
import com.yaodian100.ec.member.entity.Bonus;
import com.yaodian100.ec.member.entity.LoginHistory;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.entity.Province;
import com.yaodian100.ec.member.entity.ViewWishList;
import com.yaodian100.ec.member.entity.WishList;
import com.yaodian100.ec.member.service.AddessService;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.order.entity.OrderProduct;
import com.yaodian100.ec.order.entity.OrderProductDetail;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.service.OrderModifyService;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.order.service.ServiceOrderService;
import com.yaodian100.ec.payment.entity.BonusTransfer;
import com.yaodian100.ec.payment.service.TransferService;
import com.yaodian100.ec.product.entity.AddOnProduct;
import com.yaodian100.ec.product.entity.AddOnProductPage;
import com.yaodian100.ec.product.entity.Brand;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.entity.SpecificationInventory;
import com.yaodian100.ec.product.entity.SpecificationMajor;
import com.yaodian100.ec.product.service.Product2Service;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.rank.entity.ViewReportProductClick;
import com.yaodian100.ec.report.rank.service.ViewReportProductClickService;
import com.yaodian100.ec.search.Doc;
import com.yaodian100.ec.search.SearchManager;
import com.yaodian100.ec.search.SearchResult;
import com.yaodian100.ec.search.entity.Keyword;
import com.yaodian100.ec.shelf.entity.Shelf;
import com.yaodian100.ec.shelf.service.ShelfService;
import com.yaodian100.ec.shopping.entity.ApplyCampaign;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitMain;
import com.yaodian100.ec.timelimitsale.entity.TimeLimitProd;
import com.yaodian100.ec.timelimitsale.service.TimeLimitSaleService;
import com.yaodian100.mall.alipay.Md5Encrypt;
import com.yaodian100.mall.member.util.UserData;
import com.yaodian100.mall.search.web.SearchAction;
import com.yaodian100.mall.shopping.web.CartException;

public class YekMobileAction extends SearchAction {
	private static final long serialVersionUID = -3704189192192122370L;
	private final Logger logger = LoggerFactory.getLogger(YekMobileAction.class);
	private String XML_Result;
	private static final String MESSAGE_SESSION_INVALID = "认证数据有误";

	@Autowired
	private BaseManager baseMgr;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ImageService imageservice;
	@Autowired
	private CartOrdersService cartOrdersService;
	@Autowired
	private SearchManager searchManager;
	@Autowired
	private AnnouncementService announcementService;
	@Autowired
	private AddessService addressService;
	@Autowired
	private CartOrdersService cartordersService;
	@Autowired
	private DeliveryRuleService deliveryRuleService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private CouponService couponService;
	@Autowired
	private ProductService productService;
	@Autowired
	private ShelfService shelfService;
	@Autowired
	private BonusSettingService bonusSettingService;
	@Autowired
	private GenerateOrderService gos;
	@Autowired
	private DomainService<Menu> menuService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private ServiceOrderService serviceOrderService;
	@Autowired
	private OrderModifyService orderModifyService;
	@Autowired
	private Product2Service product2Service;
	@Autowired
	private ChannelService channelService;
	@Autowired
	private TimeLimitSaleService timeLimitSaleService;
	@Autowired
	private MailService mailService;
	@Autowired
	private TransferService transferService;
	@Autowired
	private CsService csService;
	@Autowired
	private ViewReportProductClickService viewReportProductClickService;

	private Menu systemValueMenu;// 系统参数
	private Menu paymentTpMenu;
	private Menu orderStMenu;

	private static DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

	/**
	 * 1.获取Weblogid接口
	 * 
	 * @return weblogid
	 * @Exception
	 */
	public String getweblogid() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String sourceid = request.getParameter("sourceid");
		String t = request.getParameter("t");
		String sign = request.getParameter("sign");
		String appkey = request.getParameter("appkey");

		try {
			String enc = Md5Encrypt.md5(sourceid + t);
			if (!sign.equals(enc)) {
				throw new YekMobileException("认证数据有误");
			}

			String weblogid = Md5Encrypt.md5(appkey + t);

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			x_dataset.addElement("weblogid").setText(weblogid);
			x_dataset.addElement("version").setText("1.0b");
			this.createSuccessResult(document);

			// request.getSession().setAttribute("WEBLOGID", weblogid);
			// 改使用cookie
			setValue("WEBLOGID", weblogid, false);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getweblogid error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getweblogid error :{}", e.toString());
			this.createErrorResult("失败", "认证数据有误");

		}

		return "finish";
	}

	/**
	 * 2.获取商品目录接口
	 * 
	 * @return 获取目录底下的子目录列表
	 * @throws Exception
	 */
	public String getcat() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String catid = request.getParameter("catid");
		try {
			Long id = Long.parseLong(catid);
			List<Category> list = this.categoryService.getAvailableChild(id);

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			Element x_category = x_dataset.addElement("category");
			for (Category category : list) {
				x_category.addElement("category_id").setText(category.getId().toString());
				x_category.addElement("category_name").setText(category.getName());
			}
			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcat error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcat error :{}", e.toString());
			this.createErrorResult("失败", "catid查无此ID");
		}

		return "finish";
	}

	/**
	 * 3.获取商品列表接口
	 * 
	 * @return 商品列表
	 * @throws Exception
	 */
	public String getproductbycat() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String catid = request.getParameter("catid");
		String sorttype = request.getParameter("sorttype");
		String start = request.getParameter("start");
		String size = request.getParameter("size");
		String orderSql;
		if ("aprice".equals(sorttype)) {
			orderSql = " order by RESU.shelf_price asc,RESU.product_id desc "; // 价格递增
		} else if ("dprice".equals(sorttype)) {
			orderSql = " order by RESU.shelf_price desc,RESU.product_id desc "; // 价格递减
		} else if ("asale".equals(sorttype)) {
			orderSql = " order by RESU.sold_count asc,RESU.product_id desc "; // 销售量递增
		} else if ("asale".equals(sorttype)) {
			orderSql = " order by RESU.sold_count desc,RESU.product_id desc "; // 销售量递减
		} else if ("arelat".equals(sorttype)) {
			orderSql = " order by show_seq asc,RESU.product_id desc "; // 相关度递增??相關度用甚麼排序???
		} else if ("drelat".equals(sorttype)) {
			orderSql = " order by show_seq desc,RESU.product_id desc "; // 相关度递减??相關度用甚麼排序???
		} else {
			orderSql = " order by RESU.shelf_price desc,RESU.product_id desc "; // 預設用价格递减
		}

		// 從CategoryAction copy過來的
		String countSql = "select distinct count(*) from EC_VIEW_CATEGORY_PRODUCT a,(select * from "
				+ "(select cat2.product_id, cat2.category_id, cat2.show_seq as s1,"
				+ "cat1.show_seq as s2,rank()over(partition by cat2.product_id "
				+ "order by cat2.show_seq,cat1.show_seq ) as rank  " + "from ec_category_main cat1, ec_product_category cat2 "
				+ "where cat1.category_id = cat2.category_id  " + "and cat1.category_path = cat2.category_path "
				+ "and cat1.is_delete  = 'N'  " + "and (cat1.category_path like ? or cat1.category_id=?)"
				+ "order by cat2.product_id desc) " + "where rank =1) b, ec_product_main c "
				+ "where a.product_id = b.product_id and " + " a.product_id=c.product_id and c.product_type in('0','1','7') "
				+ "and substr(a. v_uk,  (InStr(a.v_uk,'_')) +1 ) = b.category_id and "
				+ "(a.category_path like ? or a.category_id=?) " + "and (a.is_delete  = 'N' or a.is_delete = 'Q') "
				+ "order by  a.show_Seq asc,a.product_id desc";

		String sql = "SELECT * FROM(SELECT RESUL.* ,ROWNUM NUM FROM(" + "SELECT RESU.* from ("
				+ "SELECT RES.*,cs.sort_order from(" + "select distinct a.* from EC_VIEW_CATEGORY_PRODUCT a,(select * from "
				+ "(select cat2.product_id, cat2.category_id, cat2.show_seq as s1,"
				+ "cat1.show_seq as s2,rank()over(partition by cat2.product_id "
				+ "order by cat2.show_seq,cat1.show_seq ) as rank  " + "from ec_category_main cat1, ec_product_category cat2 "
				+ "where cat1.category_id = cat2.category_id  " + "and cat1.category_path = cat2.category_path "
				+ "and cat1.is_delete  = 'N'  " + "and (cat1.category_path like ? or cat1.category_id=?) "
				+ "order by cat2.product_id desc) " + "where rank =1) b,ec_product_main c "
				+ "where a.product_id = b.product_id and " + "a.product_id=c.product_id and c.product_type in('0','1','7') "
				+ "and substr(a. v_uk,  (InStr(a.v_uk,'_')) +1 ) = b.category_id and "
				+ "(a.category_path like ? or a.category_id=?) " + "and (a.is_delete  = 'N' or a.is_delete = 'Q') " + ") RES "
				+ "LEFT JOIN EC_PROD_CAT_SE cs "
				+ "ON cs.prod_cat_id=RES.prodcut_category_id and cs.category_id=? and cs.product_id=RES.product_id "
				+ ") RESU " + orderSql + " ) RESUL " + "WHERE ROWNUM<=? " + ") " + "WHERE NUM>=?";

		try {
			String tempZ = catid + "/";
			// 目录下所有商品项目数量
			int totalCount = jdbcTemplate.queryForInt(countSql, "%" + tempZ + "%", catid, "%" + tempZ + "%", catid);
			// 商品列表
			int startRow = Integer.parseInt(start);
			int endRow = startRow + Integer.parseInt(size) - 1;
			// logger.error("sql:{}", sql);
			List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, "%" + tempZ + "%", catid, "%" + tempZ + "%",
					catid, catid, endRow, startRow);
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			x_dataset.addElement("total_size").setText(String.valueOf(totalCount));

			for (Map<String, Object> product : results) {
				String productId = (String) product.get("PRODUCT_ID");
				Element x_product = x_dataset.addElement("product");
				x_product.addElement("product_id").setText(productId);
				Shelf shelf = shelfService.getShelfByProductId(productId, DateUtil.getCurrentTime(), DateUtil.getCurrentTime());
				if (null != shelf && null != shelf.getPromoteName()) {
					x_product.addElement("product_promote_name").setText(shelf.getPromoteName());
				}
				x_product.addElement("product_name").setText((String) product.get("PRODUCT_NAME"));
				x_product.addElement("list_price").setText(((BigDecimal) product.get("LIST_PRICE")).toString());
				x_product.addElement("shelf_price").setText(((BigDecimal) product.get("SHELF_PRICE")).toString());
				CommonCriteria crit = new CommonCriteria();
				crit.addEq("productId", (String) product.get("PRODUCT_ID"));
				crit.addEq("type", "MAIN");
				crit.addEq("isDelete", "N");
				List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
				boolean b = false;
				for (Image img : images) {
					if (img.getImgFilePath().indexOf("_m250") != -1) {
						x_product.addElement("image_s_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
						b = true;
						break;
					}
				}
				if (!b) {
					x_product.addElement("image_s_path").addText("");
				}
			}
			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getproductbycat error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getproductbycat error :{}", e.toString());
			this.createErrorResult("失败", "catid查无此ID");
		}

		return "finish";
	}

	/**
	 * 4.获取商品详细数据接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getproductdetail() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String productid = request.getParameter("productid");
		try {
			Product product = this.productService.get(productid);
			Shelf shelf = shelfService.getShelfByProductId(productid, DateUtil.getCurrentTime(), DateUtil.getCurrentTime());
			if (null == shelf) {
				throw new YekMobileException("此商品已下架");
			}
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			Element x_product = x_dataset.addElement("product");
			x_product.addElement("product_id").setText(productid);
			if (null != shelf && null != shelf.getPromoteName()) {
				x_product.addElement("product_promote_name").setText(shelf.getPromoteName());
			}
			x_product.addElement("product_name").setText(formatToString(product.getProductName()));

			// edit by Andy Chiang 2011/12/09
			x_product.addElement("product_text_brief").addCDATA(formatToString(product.getProductBrief()));
			x_product.addElement("product_text_desc").addCDATA(formatToString(product.getProductDescription()));
			x_product.addElement("product_text_details").addCDATA(formatToString(product.getProductDetails()));
			x_product.addElement("product_text_ordernotice").addCDATA(formatToString(product.getProductOrderNotice()));

			x_product.addElement("product_html_brief").addCDATA(productService.readFromFile(productid, "brief"));
			x_product.addElement("product_html_desc").addCDATA(productService.readFromFile(productid, "description"));
			x_product.addElement("product_html_details").addCDATA(productService.readFromFile(productid, "details"));
			x_product.addElement("product_html_ordernotice").addCDATA(productService.readFromFile(productid, "orderNotice"));

			x_product.addElement("product_keyword").setText(formatToString(product.getProductKeyword()));
			x_product.addElement("product_brand").setText(formatToString(product.getProductBrand()));
			if (product.getProductBrand() != null) {
				Brand brand = this.productService.getBrandByBrandId(product.getProductBrand());
				if (brand != null) {
					x_product.addElement("product_brand_name").setText(formatToString(brand.getBrandName()));
				} else {
					x_product.addElement("product_brand_name").setText("");
				}
			} else {
				x_product.addElement("product_brand_name").setText("");
			}
			x_product.addElement("category_path").setText(formatToString(product.getCategory().getCategoryPath()));
			if (product.getCategory().getCategoryPath() != null) {
				StringBuffer categoryPathName = new StringBuffer();
				String[] categories = product.getCategory().getCategoryPath().split("/");
				for (String catid : categories) {
					categoryPathName.append(this.categoryService.getCategoryById(Long.parseLong(catid)).getName()).append("/");
				}
				if (categoryPathName.length() > 0) {
					categoryPathName.deleteCharAt(categoryPathName.length() - 1);
				}
				x_product.addElement("category_path_name").setText(formatToString(categoryPathName.toString()));
			} else {
				x_product.addElement("category_path_name").setText("");
			}
			x_product.addElement("product_type").setText(String.valueOf(product.getProductType()));

			x_product.addElement("product_weight").setText(formatToString(product.getProductWeight()));
			x_product.addElement("list_price").setText(formatToString(product.getListPrice()));
			x_product.addElement("shelf_price").setText(formatToString(shelf.getShelfPrice()));

			if ((product.getProductType() != 6 && "N".equals(product.getCanUseCod())) || "Y".equals(product.getIsScm())) {
				x_product.addElement("canusecod").setText("N");
			} else {
				x_product.addElement("canusecod").setText("Y");
			}

			Map<String, List<AddOnProductPage>> addonProds = this.productService.getAddonProductByMainProduct(product);
			// 贈品
			List<AddOnProductPage> presents = addonProds.get("present");
			if (presents != null && presents.size() > 0) {
				Element x_gift_list = x_product.addElement("gift_list");
				for (AddOnProductPage p : presents) {
					Product present = this.productService.get(p.getAddOnProductId());
					Element x_gift = x_gift_list.addElement("gift");
					x_gift.addElement("gift_name").setText(p.getProductName());
					x_gift.addElement("gift_product_id").setText(p.getAddOnProductId());
					String[] specInfo = this.getProductSpecStr(present.getSpecifications());
					x_gift.addElement("gift_spec_id").setText(formatToString(specInfo[0]));
				}
			}
			int countSpecIsDeleteY = 0;
			if (product.getProductType() != 6) {
				// String[] specInfo = this.getProductSpecStr(product.getSpecifications());
				// x_product.addElement("specification_id").setText(formatToString(specInfo[0]));
				// x_product.addElement("specification_name").setText(formatToString(specInfo[1]));
				// x_product.addElement("specification_image").setText("");
				// x_product.addElement("specification_inventory").setText(formatToString(specInfo[2]));

				List<SpecificationMajor> specList = product.getSpecMajors();
				for (SpecificationMajor mainSpec : specList) {
					String mainName = mainSpec.getMainSpecName();
					String json = mainSpec.getJsonDetail();
					JSONArray jarray = JSONArray.fromObject(json);
					for (int i = 0; i < jarray.size(); i++) {
						String specId = JSONArray.fromObject(json).getJSONObject(i).get("specId").toString();
						String specName = mainName + "／" + JSONArray.fromObject(json).getJSONObject(i).get("specName").toString();
						x_product.addElement("specification_id").setText(specId);
						x_product.addElement("specification_name").setText(specName);

						String spechql = "from Specification where specificationId=?";
						Specification spec = (Specification) baseMgr.queryByHql(spechql, new Object[] { specId }, 0, 1)[0];

						x_product.addElement("spec_is_delete").setText(spec.getIsDelete());
						if (spec.getIsDelete().equals("Y")) {
							countSpecIsDeleteY++;
						}
						String imgIcon = mainSpec.getImgMspec();
						x_product.addElement("specification_image").setText(ServerValue.getImgDomain() + imgIcon);
						String hql = "from SpecificationInventory where specId=?";
						SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { specId }, 0, 1)[0];
						int qty = si.getAvailableInventory() + si.getCancelInventory() - si.getSoldInventory();
						if (spec.getMinCountPerOrder() > qty) {
							x_product.addElement("specification_inventory").setText("0");
						} else if (qty > spec.getMaxCountPerOrder()) {
							x_product.addElement("specification_inventory").setText(spec.getMaxCountPerOrder() + "");
						} else {
							x_product.addElement("specification_inventory").setText(qty + "");
						}
						// x_product.addElement("specification_inventory").setText(si.getInventory().toString());
					}
				}
				// 如果spec全部都停用的話，product_status設為Q
				if (countSpecIsDeleteY == specList.size()) {
					x_product.addElement("product_status").setText("Q");
				} else {
					x_product.addElement("product_status").setText(String.valueOf(product.getIsDelete())); // edit by Andy Chiang
					// Y：不可查询,不可销售, N：可查询,可销售,
					// Q：可查询,不可销售, H：不可查询,可销售
				}

			}

			CommonCriteria crit = new CommonCriteria();
			crit.addEq("productId", product.getProductId());
			// crit.addEq("type", "MAIN");
			crit.addEq("isDelete", "N");
			List<Image> images = imageservice.getList(0, -1, crit, new String[] { "id desc" });
			int b1 = 0;
			List<String> imageList = new ArrayList<String>();
			for (Image img : images) {
				if (img.getImgFilePath().indexOf("_m250") != -1) {
					if (img.getMainSpecId() == null) {
						x_product.addElement("image_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
						b1 = 1;
					}
				}
				if (null == img.getMainSpecId() && img.getType().equals("MAIN") && img.getImgFilePath().indexOf("_m500") != -1) {
					imageList.add(img.getImgFilePath());
				}
				if (img.getType().equals("DESC") && img.getImgFilePath().indexOf("_d") != -1) {
					imageList.add(img.getImgFilePath());
				}
			}
			if (b1 == 0) {
				x_product.addElement("image_path").addText("");
			}
			if (imageList.size() > 0) {
				Element x_image_ext = x_product.addElement("image_ext");
				for (String path : imageList) {
					x_image_ext.addElement("image").setText(ServerValue.getImgDomain() + path);
				}
			}
			// 本次不加入n選m,加價購
			// // n選m
			// if (product.getProductType() == 6) {
			// List<AddOnProductPage> nm = addonProds.get("nm");
			// if (nm != null && nm.size() > 0) {
			// Element x_npickm_list = x_product.addElement("npickm_list");
			// x_npickm_list.addElement("npickm_amount").setText(String.valueOf(nm.size()));
			// for (AddOnProductPage p : nm) {
			// Product nmprod = this.productService.get(p.getAddOnProductId());
			// Element x_npickm_product = x_npickm_list.addElement("npickm_product");
			// x_npickm_product.addElement("npickm_product_id").setText(formatToString(p.getAddOnProductId()));
			// x_npickm_product.addElement("npickm_product_name").setText(formatToString(p.getProductName()));
			// String[] specInfo = this.getProductSpecStr(nmprod.getSpecifications());
			// x_npickm_product.addElement("npickm_specification_id").setText(formatToString(specInfo[0]));
			// x_npickm_product.addElement("npickm_specification_name").setText(formatToString(specInfo[1]));
			// x_npickm_product.addElement("npickm_specification_inventory").setText(formatToString(specInfo[2]));
			//
			// }
			// }
			// }
			//
			// // 加價購
			// List<AddOnProductPage> addon = addonProds.get("addon");
			// if (addon != null && addon.size() > 0) {
			// Element x_addon_list = x_product.addElement("addon_list");
			// x_addon_list.addElement("addon_amount").setText(String.valueOf(addon.size()));
			// for (AddOnProductPage p : addon) {
			// Product prod = this.productService.get(p.getAddOnProductId());
			// AddOnProduct aprod = this.productService.getAddOnProduct(productid, p.getAddOnProductId());
			//
			// Element x_addon_product = x_addon_list.addElement("addon_product");
			// x_addon_product.addElement("addon_product_id").setText(formatToString(p.getAddOnProductId()));
			// x_addon_product.addElement("addon_product_name").setText(formatToString(p.getProductName()));
			// x_addon_product.addElement("addon_list_price").setText(formatToString(p.getListPrice()));
			// x_addon_product.addElement("addon_shelf_price").setText(formatToString(aprod.getAddOnPrice()));
			// String[] specInfo = this.getProductSpecStr(prod.getSpecifications());
			// x_addon_product.addElement("addon_specification_id").setText(formatToString(specInfo[0]));
			// x_addon_product.addElement("addon_specification_name").setText(formatToString(specInfo[1]));
			// x_addon_product.addElement("addonm_specification_inventory").setText(formatToString(specInfo[2]));
			// }
			// }

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getproductdetail error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getproductdetail error :{}", e.toString());
			this.createErrorResult("失败", "无此商品");
		}

		return "finish";
	}

	/**
	 * 5.获取搜寻商品结果列表接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchproduct() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		SearchResult cresult = null;
		SearchResult presult = null;

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			String keyword = request.getParameter("keyword"); // 搜寻词
			String catid = request.getParameter("catid"); // 分类id
			String sorttype = request.getParameter("sorttype"); // 排序
			String start = request.getParameter("start"); // 开始笔数
			String size = request.getParameter("size"); // 每此获取笔数
			Map<String, String> pdMap = new HashMap<String, String>();
			if (StringUtils.isBlank(keyword) && StringUtils.isBlank(catid)) {
				throw new YekMobileException("请择一输入搜寻词或分类id");
			}
			if (StringUtils.isBlank(start) || StringUtils.isBlank(size)) {
				throw new YekMobileException("请输入开始笔数,每此获取笔数");
			}

			Category category = null;
			if (catid != null && !catid.equals("0") && catid.length() > 0) {
				category = getCategory(catid);
			}

			// 查寻参数_1
			String z = catid;
			if (z != null && z.equals("0")) {
				z = null;
			}
			String searchKeyword = keyword;
			String serverName = request.getServerName();
			String applySource = null;
			String searchWithBrief = "0"; // 有1 & 0，但不知道意思，可能是true and false
			String searchWithDescription = "0";
			int categoryLevel = -1;
			if (category != null) {
				categoryLevel = Integer.valueOf(category.getLevel());
			}

			String level = String.valueOf(categoryLevel);
			if (categoryLevel == -1) {
				level = "0";
			}
			String categoryPath = "";
			if (category != null) {
				categoryPath = category.getCategoryPath();
			}
			String flag2 = null; // 立减优惠
			String flag3 = null; // 立折优惠
			String flag4 = null; // 送赠品
			String flag5 = null; // 送购物金
			String flag6 = null; // 任选商品
			String flag7 = null; // 加购商品
			String minPrice = null; // 上价档价位下限
			String maxPrice = null; // 上价档价位上限
			String startDate = null;
			String endDate = null;
			String flag1 = null; // 不包含预购
			// String partner = "DAPHNE"; // 门店取货，用来判断是不是达芙尼取货
			String partner = null;
			String brandId = null;

			int pageSize = Integer.parseInt(size);
			if (pageSize > 100) {
				pageSize = 100;
			}

			// 所在页数
			int pindex = ((Integer.parseInt(start) - 1) / pageSize) + 1;
			String pIndex = String.valueOf(pindex);

			// 设定查寻用类目id
			String catId = z;
			if (catId != null && catId.equals("0")) {
				catId = "";
			}

			// 排序条件转换
			String sortOrderType;
			if (sorttype == null) {
				sortOrderType = "3";
			} else if (sorttype.equals("aprice")) {
				sortOrderType = "2";
			} else if (sorttype.equals("dprice")) {
				sortOrderType = "3";
			} else if (sorttype.equals("asale")) {
				sortOrderType = "5";
			} else if (sorttype.equals("dsale")) {
				sortOrderType = "4";
			} else if (sorttype.equals("arelat")) {
				sortOrderType = "6";
			} else if (sorttype.equals("drelat")) {
				sortOrderType = "6";
			} else {
				sortOrderType = "3";
			}

			String querytype = "";
			int pagesize = pageSize;
			String orderby = searchManager.orderSyntax(searchKeyword, sortOrderType);
			String queryoption = "";
			String countquery = "";
			String displayfields = "";
			String weightsyntax = "";

			String blocksyntax = searchManager.blockSyntax_V2(z, searchKeyword, serverName, applySource, searchWithBrief,
					searchWithDescription, level, categoryPath, flag2, flag3, flag4, flag5, null, null, minPrice, maxPrice,
					startDate, endDate, flag1, partner, brandId);

			// 设定父类目id
			String parentCatId = "";
			if (category != null) {
				String[] categoryIds = category.getCategoryPath().split("/");
				// if (categoryIds.length > 2) {
				// parentCatId = categoryIds[categoryIds.length - 2];
				if (categoryLevel > 0) {
					parentCatId = categoryIds[categoryLevel - 1];
				} else {
					parentCatId = "";
				}
				// } else {
				// parentCatId = "";
				// }
			}

			String searchKeywordU = JspUtil.urlDecoding(searchKeyword, "UTF-8");
			if (categoryLevel != -1 || (brandId != null && brandId.length() > 0)
					|| (searchKeyword != null && searchKeyword.length() > 0)) {
				int theCl = -1;
				if (categoryLevel != -1) {
					theCl = categoryLevel - 1;
				}

				Category parentCategory = getCategory(parentCatId);
				String parentLevel = "0";
				String parentCategoryPath = "";
				if (parentCategory != null) {
					parentCategory.getLevel();
					parentCategory.getCategoryPath();
				}

				String blockSyntax_0 = searchManager.blockSyntax_V2(parentCatId, searchKeyword, serverName, applySource,
						searchWithBrief, searchWithDescription, parentLevel, parentCategoryPath, flag2, flag3, flag4, flag5, null,
						null, minPrice, maxPrice, startDate, endDate, flag1, partner, brandId);
				// if (partner != null && partner.length() > 0) {
				// theCl = -1;
				// parentCatId = "";
				// }
				cresult = searchManager.query(theCl, parentCatId, searchKeywordU, querytype, Integer.parseInt(pIndex), 1,
						blockSyntax_0, orderby, queryoption, countquery, displayfields, weightsyntax, false);
			}

			if (searchKeyword != null && searchKeyword.length() > 0 || z != null || (brandId != null && brandId.length() > 0)) {
				// if (partner != null && partner.length() > 0) {
				// categoryLevel = -1;
				// catId = "";
				// }
				presult = searchManager.query(categoryLevel, catId, searchKeywordU, querytype, Integer.parseInt(pIndex),
						pagesize, blocksyntax, orderby, queryoption, countquery, displayfields, weightsyntax, false);

				// if (getPager() == null) {
				// setPager(new SimplePager(2));
				// }
				// getPager().setPageRecord(pagesize);
				// getPager().setTotalSize(result1.getTotal());
				// if (result1.getTotal() == 0) {
				// // fuzzySearch count
				// queryoption = "'FuzzySearch'";
				// SearchResult r = searchManager.query(-1, "", searchKeywordU, "", 0, 10, "", "", queryoption, "", "", "",
				// false);
				// }
			}
			/*
			 * "由于此次暂不提供任选与加购商品服务 接口3.获取商品列表接口与 接口5.获取搜寻商品结果列表接口 需过滤掉任选与加价购商品。"
			 */
			if (presult.getTotal() > 0) {
				List<String> ids = new ArrayList<String>();
				for (Doc p : presult.getDocs()) {
					ids.add(p.getProductId());
				}
				CommonCriteria crit = new CommonCriteria();
				crit.addIn("productId", ids);
				List<Product> products = product2Service.getList(0, -1, crit, null);
				for (Product pd : products) {
					if (Arrays.asList(new String[] { "0", "1", "7" }).contains(String.valueOf(pd.getProductType()))) {
						pdMap.put(pd.getProductId(), "OK");
					}
				}
			}

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			x_dataset.addElement("total_size").setText(String.valueOf(pdMap.size()));
			if (cresult.getTotal() > 0) {
				Element x_category_search = x_dataset.addElement("category_search");
				for (com.yaodian100.ec.search.Category c : cresult.getCategories()) {
					if (c.getDisplayName().indexOf(",") > 0 && c.getCqCount() > 0) {
						Element x_category = x_category_search.addElement("category");
						String[] carInfo = c.getDisplayName().split(",");
						x_category.addElement("category_id").setText(carInfo[0]);
						x_category.addElement("category_name").setText(carInfo[1]);
						x_category.addElement("search_amount").setText(String.valueOf(c.getCqCount()));
					}
				}
				for (Doc p : presult.getDocs()) {
					if ("OK".equals(pdMap.get(p.getProductId()))) {
						Element x_product = x_dataset.addElement("product");
						x_product.addElement("product_id").setText(p.getProductId());
						x_product.addElement("product_name").setText(p.getProductName());
						x_product.addElement("list_price").setText(formatToString(p.getListPrice()));
						x_product.addElement("shelf_price").setText(formatToString(p.getShelfPrice()));
						CommonCriteria crit = new CommonCriteria();
						crit.addEq("productId", p.getProductId());
						crit.addEq("type", "MAIN");
						crit.addEq("isDelete", "N");
						List<Image> images = imageservice.getList(1, -1, crit, new String[] { "id desc" });
						int b1 = 0;
						for (Image img : images) {
							if (img.getImgFilePath().indexOf("_m75") != -1) {
								x_product.addElement("image_s_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
								b1 = 1;
								break;
							}
						}
						if (b1 == 0) {
							x_product.addElement("image_s_path").addText("");
						}
					}
				}
			}
			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.searchhotterm error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.searchhotterm error :{}", e.toString());
			this.createErrorResult("失败", "获取数据失败");
		}

		return "finish";
	}

	/**
	 * 6.获取热门搜寻关键词接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchhotterm() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			String hql = "from Keyword where categoryId=?";
			Keyword kwd = (Keyword) baseMgr.queryByHql(hql, new Object[] { "0" }, 0, 1)[0];
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			Element x_hotterms = x_dataset.addElement("hotterms");
			for (String key : kwd.getWords()) {
				x_hotterms.addElement("hotterm").setText(formatToString(key));
			}
			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.searchhotterm error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.searchhotterm error :{}", e.toString());
			this.createErrorResult("失败", "获取数据失败");
		}

		return "finish";
	}

	/**
	 * 7.获取秒杀商品列表接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String timelimitsalelist() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			DateFormat df = new SimpleDateFormat("yyyyMMdd");
			DateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");

			Calendar cld = Calendar.getInstance();
			Date dtu = cld.getTime();
			String date = df2.format(dtu);
			Date time = df.parse(StringUtils.substring(date, 0, 8));
			Date genTime = df2.parse(date);

			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("saleDate", time);
			criteria.addEq("categoryID", 0);

			List<TimeLimitMain> tlmList = timeLimitSaleService.getList(0, -1, criteria, null);
			criteria = new CommonCriteria();
			if (tlmList.size() == 0) {
				throw new YekMobileException("無秒杀商品");
			}
			criteria.addEq("mainId", tlmList.get(0).getId());
			List<TimeLimitProd> tlpList = timeLimitSaleService.getTimeLimitProdList(criteria,
					new String[] { "startDate asc" }, 0, -1);

			// 检查库存 & 结束时间
			Map<String, String> qtyMap = new HashMap<String, String>();
			Map<String, String> prodTypeMap = new HashMap<String, String>();
			List<String> errProd = new ArrayList<String>();
			// Map<String, Date> endTimeMap = new HashMap<String, Date>();
			for (int i = 0; i < tlpList.size(); i++) {
				TimeLimitProd tlp = tlpList.get(i);
				tlp.setTmpEndDate(tlp.getEndDate());
				if ((i < tlpList.size() - 1) && tlpList.get(i + 1).getIsRepeat().equals("Y")) {
					i++;
					for (int j = i; j < tlpList.size(); j++) {
						if (tlpList.get(j).getIsRepeat().equals("Y")) {
							tlp.setTmpEndDate(tlpList.get(j).getEndDate());
						} else {
							i = j - 1;
							break;
						}
					}
				}
				if (tlp.getIsRepeat().equals("N") && (!qtyMap.containsKey(tlp.getProductId()))) {
					int qty = 0;
					Map<String, SpecificationInventory> smap = productService.getSpecificationInventoryMap(tlp.getProductId());
					if (!smap.isEmpty()) {
						Set<String> key = smap.keySet();
						for (Iterator<String> it = key.iterator(); it.hasNext();) {
							String name = it.next();
							SpecificationInventory sp = smap.get(name);
							qty += (sp.getAvailableInventory() - sp.getSoldInventory() + sp.getCancelInventory());
						}
						qtyMap.put(tlp.getProductId(), Integer.toString(qty));

						// 发信资讯
						Product p = productService.get(tlp.getProductId());
						if (tlp.getStartDate().getTime() > genTime.getTime()
								&& (qty == 0 || ("Y".equals(p.getIsDelete()) || "H".equals(p.getIsDelete())))) {
							errProd.add(tlp.getProductId());
							prodTypeMap.put(tlp.getProductId(), p.getIsDelete());
						}
						// 抢购中商品
						if (tlp.getStartDate().getTime() <= genTime.getTime() && tlp.getTmpEndDate().getTime() > genTime.getTime()) {
							Shelf s = shelfService.getShelfByProductId(tlp.getProductId(), DateUtil.getCurrentTime(),
									DateUtil.getCurrentTime());
							if (null == s) {
								// checkShelf = "秒杀中商品:" + tlp.getProductId() + " 未上架";
							} else if (s.getShelfPrice().compareTo(tlp.getLimitPrice()) != 0) {
								// checkShelf = "秒杀中商品:" + tlp.getProductId() + " 秒杀价:" + tlp.getLimitPrice() + " 卖场价格:" +
								// s.getShelfPrice();
							}
						}
					}
				}
			}
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			for (TimeLimitProd prod : tlpList) {
				Element x_product = x_dataset.addElement("product");
				x_product.addElement("product_id").setText(formatToString(prod.getProductId()));
				x_product.addElement("product_name").setText(formatToString(prod.getProductName()));
				x_product.addElement("limit_price").setText(formatToString(prod.getLimitPrice()));
				x_product.addElement("member_price").setText(formatToString(prod.getMemberPrice()));
				x_product.addElement("start_date").setText(formatTimeToString(prod.getStartDate()));
				x_product.addElement("end_date").setText(formatTimeToString(prod.getEndDate()));
				if (qtyMap.get(prod.getProductId()) != null) {
					x_product.addElement("qty").addText(String.valueOf(qtyMap.get(prod.getProductId())));
				} else {
					x_product.addElement("qty").addText("");
				}

				CommonCriteria crit = new CommonCriteria();
				crit.addEq("productId", prod.getProductId());
				crit.addEq("type", "MAIN");
				crit.addEq("isDelete", "N");
				List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
				int b1 = 0;
				int b2 = 0;
				for (Image img : images) {
					if (img.getImgFilePath().indexOf("_m250") != -1) {
						x_product.addElement("image_s_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
						b1 = 1;
						break;
					} else if (img.getImgFilePath().indexOf("_m135") != -1) {
						// x_product.addElement("image_l_path").addText(img.getImgFilePath());
						b2 = 1;
					}
				}
				if (b1 == 0) {
					x_product.addElement("image_s_path").addText("");
				}
				if (b2 == 0) {
					// x_product.addElement("image_l_path").addText("");
				}
			}
			x_dataset.addElement("genTime").setText(df2.format(new Date()));
			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.timelimitsalelist error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.timelimitsalelist error :{}", e.toString());
			this.createErrorResult("获取数据失败");
		}

		return "finish";
	}

	/**
	 * 8.执行会员登入接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			String userId = request.getParameter("userid");
			String password = request.getParameter("password");

			Member member = this.memberService.getMemberByLoginId(userId);
			if (member == null) {
				throw new YekMobileException("帐号不存在");
			}

			if ("nonmember".equals(member.getApplySource()) && null == member.getActivateExpireDate()) {
				throw new YekMobileException("非会员");
			}

			UserData userData = new UserData(request, response);
			// get ip
			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			String clientIp = StringUtils.isBlank(host) ? "" : (host.length() > 100 ? host.substring(0, 100) : host);
			if (!member.getPwd().equals(password)) {
				memberService.saveFrontendLoginHistory(member, clientIp, "2");
				throw new YekMobileException("密码错误");
			}

			if (member.getActiveDate() == null) {
				throw new YekMobileException("帐号未激活");
			}

			LoginHistory loginHistory = memberService.getLastLoginHistory(member.getLoginId());
			if (null != loginHistory) {
				member.setLastLoginTime(loginHistory.getLoginTime());
				memberService.update(member);
				memberService.deleteLoginHistory(member.getLoginId());
			}
			memberService.saveFrontendLoginHistory(member, clientIp);
			memberService.checkLoginBonus(member, request.getServerName(), userData.getApplySource());
			userData.setLoginId(member.getLoginId());
			userData.setMemberId(member.getMemberId());
			userData.setNickname(userId);

			// 检查购物车，若为空，直接产生一个
			CartOrders cartOrders = cartOrdersService.getCart(member.getMemberId(), member.getMemberId() + "_yekmobile");

			if (cartOrders == null || member.getMemberId().equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(member.getMemberId() + "_yekmobile", null, null, null, 0, null, null);
			}
			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			x_dataset.addElement("weblogid").setText(request.getParameter("weblogid"));
			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.login error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.login error :{}", e.toString());
			// this.createErrorResult("失败", "认证数据有误");
			this.createErrorResult("失败", "认证数据有误4<!---" + e.toString() + "-->");
		}

		return "finish";
	}

	/**
	 * 9.执行会员注销接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String logout() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			userData.clearAll();

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			x_dataset.addElement("weblogid").setText(request.getParameter("weblogid"));
			this.createSuccessResult(document, "注销成功");

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.logout error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.logout error :{}", e.toString());
			this.createErrorResult("失败", "注销认证数据有误");
		}

		return "finish";
	}

	/**
	 * 10.提交会员注册接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String register() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			String userId = request.getParameter("userid");
			String password = request.getParameter("password");
			String registertype = request.getParameter("registertype");
			String phoneno = request.getParameter("phoneno");
			String email = request.getParameter("email");
			Member member = new Member();

			UserData userData = new UserData(request, response);

			if (registertype.equals("phone") && StringUtils.isBlank(phoneno)) {
				throw new YekMobileException("请输入手机号码");
			}

			if (registertype.equals("email") && StringUtils.isBlank(email)) {
				throw new YekMobileException("请输入email");
			}

			if (memberService.isLoginExist(userId)) {
				throw new YekMobileException("帐号重复");
			}
			if (registertype.equals("phone")) {
				if (memberService.isMobileExist(phoneno, null)) {
					throw new YekMobileException("手机重复");
				}
				member.setMobile(phoneno);
				member.setTempEmail(email);
			} else if (registertype.equals("email")) {
				if (memberService.isEmailExist(email)) {
					throw new YekMobileException("mail重复");
				}
				member.setEmail(email);
			} else {
				throw new YekMobileException("注册型态有误");
			}

			member.setLoginId(userId);
			member.setPwd(password);
			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			String aps = userData.getApplySource();
			if (StringUtils.isBlank(aps)) {
				member.setApplySource("yekmobile");
				member.setChannelId(Long.parseLong("0"));
				member.setChannelChild(null);
			} else {
				member.setApplySource(aps);
				String ch_id = userData.readValue("ch_id");
				if (StringUtils.isNotBlank(ch_id)) {
					member.setChannelId(Long.parseLong(ch_id));
				} else {
					member.setChannelId(channelService.getActivateChannelIdByName(aps));
				}
				member.setChannelChild(userData.getChChildCookie());
			}
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);

			logger.debug("register cookie == " + new Date().toString() + "  host():" + host + ", apply source{}:" + aps
					+ ", loginId{}:" + userId);

			// if (registertype.equals("phone")) {
			// member = memberService.saveMobileMember(member, false);
			// } else {
			// member = memberService.saveMember(member, false);
			// }
			// 由於廠商建議帳號申請採快速通關方式跳過激活作業，經由高層主管同意，將會員申請接口改成直接帳號開通不需要激活。
			member.setRank("1");
			member.setStatus("00");
			member.setActivateExpireDate(new java.sql.Date(DateUtils.addDays(new Date(), 7).getTime()));
			member.setActiveDate(new java.sql.Date(DateUtils.addDays(new Date(), 0).getTime()));
			member = memberService.save(member);
			memberService.newBalance(member);
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			x_dataset.addElement("weblogid").setText(request.getParameter("weblogid"));
			this.createSuccessResult(document, "注册成功");

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.logout error :{}", e.toString());
			this.createErrorResult("注册失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.logout error :{}", e.toString());
			this.createErrorResult("注册失败", "注册数据有误");
		}

		return "finish";
	}

	/**
	 * 10a.再次申请激活码接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String reqactivecode() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			String userId = request.getParameter("userid");
			String phoneno = request.getParameter("phoneno");
			String registertype = request.getParameter("registertype");
			String email = request.getParameter("email");
			// String password = request.getParameter("password"); 暂时不需要提供
			Member member = new Member();

			UserData userData = new UserData(request, response);

			if (userId != null) {
				memberService.getMemberByLoginId(userId);
			} else {
				throw new YekMobileException("无提供帐号ID");
			}

			if (registertype.equals("phone")) {
				if (phoneno == null) {
					throw new YekMobileException("无提供帐号手机号码");
				}
				memberService.resendRegActivateSMS(member, phoneno);
			} else if (registertype.equals("email")) {
				if (email == null) {
					throw new YekMobileException("无提供帐号电邮");
				}
				memberService.resendRegActivateMail(member, email, null); // password 传 null将不检查帐号合法性
			}

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			x_dataset.addElement("weblogid").setText(request.getParameter("weblogid"));
			this.createSuccessResult(document, "重送激活码成功");

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.logout error :{}", e.toString());
			this.createErrorResult("再次申请激活失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.logout error :{}", e.toString());
			this.createErrorResult("再次申请激活失败", "申请激活程序发生问题，请稍后再试");
		}

		return "finish";
	}

	/**
	 * 11.激活会员注册接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String actaccount() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		// HttpServletResponse response = (HttpServletResponse)
		// ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			String userid = request.getParameter("userid");
			String confirmcode = request.getParameter("confirmcode");
			// String phoneno = request.getParameter("phoneno");

			Member member = memberService.setMobileMemberActive(userid, confirmcode);
			if (member == null) {
				throw new YekMobileException("验证码有误");
			}

			// 產生XML
			Document document = DocumentHelper.createDocument();
			document.addElement("dataset");
			this.createSuccessResult(document, "激活成功");

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.actaccount error :{}", e.toString());
			this.createErrorResult("注册失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.actaccount error :{}", e.toString());
			this.createErrorResult("注册失败", "验证码有误");
		}

		return "finish";
	}

	/**
	 * 12.获取购物车列表接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String golistCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		List<CartOrderProduct> cartOrderProductList = null;

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			CartOrders cartOrders = cartOrdersService.getCart(memberId, memberId + "_yekmobile");
			if (null == cartOrders || memberId.equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			}
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			if (cartOrders != null) {
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				// optional.put("domain", "www.yaodian100.com");
				// optional.put("cookie", "yaodian100");
				cartOrders = cartOrdersService.calculateCart(cartOrders, optional); // 每次從新計算shopping cart的金額

				cartOrderProductList = cartOrders.getCartOrderProducts();
				CommonCriteria crit = new CommonCriteria();

				x_dataset.addElement("shopcartid").setText(cartOrders.getCartId().split("_")[0]); // 购物车ID
				List<CartOrderProduct> overbuyList = new ArrayList<CartOrderProduct>();
				BigDecimal totalDiscount = BigDecimal.ZERO;
				BigDecimal totalUnitPrict = BigDecimal.ZERO;
				for (CartOrderProduct cartOrderProduct : cartOrderProductList) {
					totalDiscount = totalDiscount.add(cartOrderProduct.getDiscount());
					totalUnitPrict = totalUnitPrict.add(cartOrderProduct.getUnitPrice().multiply(
							new BigDecimal(cartOrderProduct.getQty())));
					if (cartOrderProduct.getProdTp().equals("5")) {
						overbuyList.add(cartOrderProduct);
						continue;
					}
					List<String> tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());

					Element x_shoppingcart = x_dataset.addElement("shoppingcart");
					x_shoppingcart.addElement("cart_id").setText(formatToString(cartOrders.getCartId().split("_")[0]));
					x_shoppingcart.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_shoppingcart.addElement("cart_order_product_id").setText(
							formatToString(cartOrderProduct.getCartOrderProdId()));
					x_shoppingcart.addElement("campaign_id").setText(formatToString(cartOrderProduct.getCampaignId()));
					x_shoppingcart.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					x_shoppingcart.addElement("campaign_name").setText(formatToString(cartOrderProduct.getCampaignName()));
					x_shoppingcart.addElement("category_Path").setText(formatToString(cartOrderProduct.getCategoryPath()));
					int c = 0;
					if (tlpList != null) {
						for (int b = 0; b < tlpList.size(); b++) {
							if (tlpList.get(b).equals(cartOrderProduct.getProdId())) {
								x_shoppingcart.addElement("promote_name").setText("timelimitsales");
								c = 1;
							}
						}
					}
					if (c == 0) {
						x_shoppingcart.addElement("promote_name").setText("");
					}
					x_shoppingcart.addElement("product_spec_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_shoppingcart.addElement("product_spec_name").setText(formatToString(cartOrderProduct.getProdSpecName()));
					x_shoppingcart.addElement("product_Tp").setText(formatToString(cartOrderProduct.getProdTp()));

					x_shoppingcart.addElement("discount").setText(String.valueOf(cartOrderProduct.getDiscount()));
					x_shoppingcart.addElement("qty").addText(String.valueOf(cartOrderProduct.getQty()));
					x_shoppingcart.addElement("unit_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_shoppingcart.addElement("total_price").setText(formatToString(cartOrderProduct.getTotalPrice()));
					Product product = product2Service.get(cartOrderProduct.getProdId());
					if ((product.getProductType() != 6 && "N".equals(product.getCanUseCod())) || "Y".equals(product.getIsScm())) {
						x_shoppingcart.addElement("canusecod").setText("N");
					} else {
						x_shoppingcart.addElement("canusecod").setText("Y");
					}
					crit.addEq("productId", formatToString(cartOrderProduct.getProdId()));
					crit.addEq("type", "MAIN");
					crit.addEq("isDelete", "N");
					List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
					int b1 = 0;
					for (Image img : images) {
						if (img.getImgFilePath().indexOf("_m135") != -1) {
							x_shoppingcart.addElement("image_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
							b1 = 1;
							break;
						}
					}
					if (b1 == 0) {
						x_shoppingcart.addElement("image_path").addText("");
					}
					// 廠商強烈建議在購物車中加入購物車中商品的庫存數量才能讓購物車直接操作數量修改增加使用的的體驗值
					SpecificationInventory specificationInventory = new SpecificationInventory();
					specificationInventory = productService.getSpecificationInventory(cartOrderProduct.getProdId(),
							Long.parseLong(cartOrderProduct.getProdSpecId()));
					int availableInventory = specificationInventory.getInventory();
					x_shoppingcart.addElement("specification_inventory").setText(formatToString(availableInventory));
					List<CartOrderProductDetail> details = cartOrderProduct.getDetails();
					for (CartOrderProductDetail prodDetail : details) {
						if (prodDetail.getDetailTp().equals("2")) {
							Element x_gift = x_shoppingcart.addElement("gift");
							x_gift.addElement("gift_product_id").setText(prodDetail.getProdId());
							x_gift.addElement("gift_product_name").setText(prodDetail.getProdName());
							x_gift.addElement("gift_product_image").setText(
									ServerValue.getImgDomain() + "/PImg/" + prodDetail.getProdId().substring(0, 4) + "/"
											+ prodDetail.getProdId() + "/" + prodDetail.getProdId() + "_m135.jpg");
						}
					}

					if ("6".equals(cartOrderProduct.getProdTp())) { // n-m
						for (CartOrderProductDetail prodDetail : details) {
							Element x_npickm = x_shoppingcart.addElement("npickm");
							x_npickm.addElement("npickm_product_id").setText(prodDetail.getProdId());
							x_npickm.addElement("npickm_product_name").setText(prodDetail.getProdName());
							x_npickm.addElement("npickm_specification_id").setText(prodDetail.getProdSpecId());
							x_npickm.addElement("npickm_specification_name").setText(prodDetail.getProdSpecName());
							x_npickm.addElement("npickm_product_image").setText(
									ServerValue.getImgDomain() + "/PImg/" + prodDetail.getProdId().substring(0, 4) + "/"
											+ prodDetail.getProdId() + "/" + prodDetail.getProdId() + "_m135.jpg");
						}
					}
				}

				for (CartOrderProduct cartOrderProduct : overbuyList) {
					Element x_overbuy = x_dataset.addElement("overbuy");
					x_overbuy.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_overbuy.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					Shelf shelf = shelfService.getShelfByProductId(cartOrderProduct.getProdId(), DateUtil.getCurrentTime(),
							DateUtil.getCurrentTime());
					x_overbuy.addElement("shelf_price").setText(formatToString(shelf.getShelfPrice()));
					x_overbuy.addElement("overbuy_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_overbuy.addElement("specification_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_overbuy.addElement("specification_name").setText(formatToString(cartOrderProduct.getProdSpecName()));
				}

				Element x_summary = x_dataset.addElement("summary");
				x_summary.addElement("totalcount").setText(formatToString(cartOrders.getProductSum()));// 商品总数量
				x_summary.addElement("totalweight").setText(formatToString(cartOrders.getWeightSum()));// 重量总计
				x_summary.addElement("cheap").setText(formatToString(totalDiscount));// 折抵金额
				x_summary.addElement("totalsum").setText(formatToString(totalUnitPrict.subtract(totalDiscount)));// 合计金额

			}

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误");
		}

		return "finish";
	}

	public String test() throws Exception {
		String hql = "from com.yaodian100.ec.product.entity.AddOnProduct o where o.addOnPrice=? and o.isDelete=? and o.mainProductId=?";
		this.baseMgr.queryByHql(hql, new Object[] { new Integer(-1), "N", "00138898" });
		return null;
	}

	/**
	 * 13.提交商品至购物车接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			// String memberId = "0000763652";

			Member member = memberService.get(memberId);
			if (member == null) {
				throw new YekMobileException("无登入讯息");
			}

			String catid = request.getParameter("catid");
			String productid = request.getParameter("productid");
			String specCode = request.getParameter("specification_code");
			String qty = request.getParameter("qty");
			String producttype = request.getParameter("producttype");
			String cartid = request.getParameter("cartid");
			String giftPdId = request.getParameter("gift_pd_id");
			String giftSpecId = request.getParameter("gift_spec_id");
			String npmPdId = request.getParameter("npm_pd_id");
			String npmSpecId = request.getParameter("npm_spec_id");
			String addonPdId = request.getParameter("addon_pd_id");
			String addonSpecId = request.getParameter("addon_spec_id");

			List<String> addOnProductIds = new ArrayList<String>();
			if (!"6".equals(producttype)) {
				if (addonPdId != null && addonPdId.length() > 0) {
					String[] addOnsSplit = addonPdId.split(",");
					String[] addOnsSpecSplit = addonSpecId.split(",");
					for (int i = 0; i < addOnsSplit.length; i++) {
						// 此次不加入加購商品
						// addOnProductIds.add(addOnsSplit[i] + ";" + addOnsSpecSplit[i]);
					}
				}
			} else {
				if (npmPdId != null && npmPdId.length() > 0) {
					String[] nmSplit = npmPdId.split(",");
					String[] nmSpecSplit = npmSpecId.split(",");
					for (int i = 0; i < nmSplit.length; i++) {
						// 此次不加n选m商品
						// addOnProductIds.add(nmSplit[i] + ";" + nmSpecSplit[i]);
					}
				}
			}

			CartOrders cartOrders;
			if (cartid != null && cartid.length() > 0) {
				cartOrders = this.cartOrdersService.getCart(memberId, cartid + "_yekmobile");
			} else {
				cartOrders = this.cartOrdersService.getCart(memberId, memberId + "_yekmobile");
			}
			if (null == cartOrders || memberId.equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			}
			if (null == cartOrders) { // 已登入且會員從未加入過購物車
				cartOrders = cartOrdersService.createCartForStep1(memberId, null, null, null, 0, null, null); // 新增一個購物車
			}

			boolean isItemExist = false;
			if (!"6".equals(producttype)) {
				for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
					if (cop.getProdSpecId().equals(specCode)) {
						isItemExist = true;
						break;
					}
				}
			}
			if (!isItemExist) { // 加入購物車
				if (!"6".equals(producttype)) {
					cartOrders = cartOrdersService.addProductForStep1(member.getMemberId(), cartOrders.getCartId(), productid,
							null, Long.valueOf(specCode), Integer.valueOf(qty), catid, addOnProductIds);
				} else {
					cartOrders = cartOrdersService.addProductForStep1(member.getMemberId(), cartOrders.getCartId(), productid,
							addOnProductIds, null, 1, catid, null);
				}
				// 记录商品類別cookie
				if (catid != null) { // edit by Andychiang
					userData.writeRawValue("fromProduct",
							categoryService.get(Long.parseLong(catid)).getCategoryPath().split("/")[0]);
				}
			} else { // 修改
				String hql = "from SpecificationInventory where specId=?";
				String cartMessage = "";
				for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
					// 加購商品更改數量
					if (addonPdId != null && addonPdId.length() > 0) {
						for (CartOrderProductDetail copd : cop.getDetails()) {
							if (copd.getProdId().equals(addonPdId)) {
								// 檢查庫存
								SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql,
										new Object[] { copd.getProdSpecId() }, 0, 1)[0];
								Integer inventory = si.getInventory();
								// do something
								if (inventory <= 0) {
									// 庫存不足
									cartMessage += "庫存不足無法購買！";
									copd.setQty(0);
								} else if (inventory < Integer.parseInt(qty)) {
									// 庫存量少於所選數量
									cartMessage += "庫存数量不足于所选的数量，已调整为：" + inventory;
									copd.setQty(inventory);
								} else {
									copd.setQty(Integer.parseInt(qty));
								}
								break;
							}
						}
					} else {
						// 主商品更改數量，prodSpecId要一併傳回
						if (qty != null) {
							if (cop.getProdId().equals(productid) && cop.getProdSpecId().equals(specCode)) {
								Integer selectProdQty = Integer.parseInt(qty);
								// 檢查庫存
								CartOrderProduct copCurrent = (CartOrderProduct) baseMgr.get(CartOrderProduct.class,
										cop.getCartOrderProdId());
								SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql,
										new Object[] { copCurrent.getProdSpecId() }, 0, 1)[0];
								Integer inventory = si.getInventory();
								if (inventory <= 0) {
									cartMessage += "所选属性库存不足";
								} else {
									if (selectProdQty > inventory) {
										// 庫存量少於所選數量
										cartMessage += "库存不足";// ，已调整为：" + inventory;
										// cop.setProdSpecId(specCode);
										// cop.setQty(inventory);
									} else {
										cop.setQty(selectProdQty);
										// cop.setProdSpecId(specCode);
										// cop.setProdSpecName(si.getSpecification().getSpecificationName());
									}
									cartMessage += updateCartDetail(cop, copCurrent);
									break;
								}
							}
						}
					}

				}
				if (!cartMessage.equals("")) {
					throw new YekMobileException(cartMessage);
				}
				cartOrdersService.update(cartOrders);
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				cartOrders = cartOrdersService.calculateCart(cartOrders, optional);
			}

			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));

			// 產生XML
			Document document = DocumentHelper.createDocument();
			document.addElement("dataset");

			this.createSuccessResult(document, "新增项目成功");

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.addCart error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.addCart error :{}", e.toString());
			this.createErrorResult("提交失败", "提交数据有误");
		}

		return "finish";
	}

	/**
	 * 修改商品数量至购物车接口 TODO 目前只能一次一笔
	 * 
	 * @return
	 * @throws Exception
	 */
	public String updateCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			// String memberId = "0000763652";

			Member member = memberService.get(memberId);
			if (member == null) {
				throw new YekMobileException("无登入讯息");
			}

			String catid = request.getParameter("catid");
			String productid = request.getParameter("productid");
			String specCode = request.getParameter("specification_code");
			String qty = request.getParameter("qty");
			String producttype = request.getParameter("producttype");
			String cartid = request.getParameter("cartid");
			String giftPdId = request.getParameter("gift_pd_id");
			String giftSpecId = request.getParameter("gift_spec_id");
			String npmPdId = request.getParameter("npm_pd_id");
			String npmSpecId = request.getParameter("npm_spec_id");
			String addonPdId = request.getParameter("addon_pd_id");
			String addonSpecId = request.getParameter("addon_spec_id");

			List<String> addOnProductIds = new ArrayList<String>();
			if (!"6".equals(producttype)) {
				if (addonPdId != null && addonPdId.length() > 0) {
					String[] addOnsSplit = addonPdId.split(",");
					String[] addOnsSpecSplit = addonSpecId.split(",");
					for (int i = 0; i < addOnsSplit.length; i++) {
						// addOnProductIds.add(addOnsSplit[i] + ";" + addOnsSpecSplit[i]);
					}
				}
			} else {
				if (npmPdId != null && npmPdId.length() > 0) {
					String[] nmSplit = npmPdId.split(",");
					String[] nmSpecSplit = npmSpecId.split(",");
					for (int i = 0; i < nmSplit.length; i++) {
						// addOnProductIds.add(nmSplit[i] + ";" + nmSpecSplit[i]);
					}
				}
			}

			CartOrders cartOrders;
			if (cartid != null && cartid.length() > 0) {
				cartid = cartid + "_yekmobile";
				cartOrders = this.cartOrdersService.getCart(memberId, cartid);
			} else {
				cartOrders = this.cartOrdersService.getCart(memberId, memberId + "_yekmobile");
			}
			if (memberId.equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			}
			if (null == cartOrders) { // 已登入且會員從未加入過購物車
				cartOrders = cartOrdersService.createCartForStep1(memberId, null, null, null, 0, null, null); // 新增一個購物車
			}

			boolean isItemExist = false;
			if (!"6".equals(producttype)) {
				for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
					// if (cop.getProdId().equals(itemNo[0])) {
					if (cop.getProdSpecId().equals(specCode)) {
						isItemExist = true;
						break;
					}
				}
			}
			if (!isItemExist) { // 加入購物車
				if (!"6".equals(producttype)) {
					cartOrders = cartOrdersService.addProductForStep1(member.getMemberId() + "_yekmobile",
							cartOrders.getCartId(), productid, null, Long.valueOf(specCode), Integer.valueOf(qty), catid,
							addOnProductIds);
				} else {
					cartOrders = cartOrdersService.addProductForStep1(member.getMemberId() + "_yekmobile",
							cartOrders.getCartId(), productid, addOnProductIds, null, 1, catid, null);
				}
				// 记录商品類別cookie
				userData.writeRawValue("fromProduct",
						categoryService.get(Long.parseLong(catid)).getCategoryPath().split("/")[0]);
			} else { // 修改
				String hql = "from SpecificationInventory where specId=?";
				String cartMessage = "";
				for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
					if (cop.getProdId().equals(productid) && cop.getProdSpecId().equals(specCode)) {
						// 加購商品更改數量
						if (addonPdId != null && addonPdId.length() > 0) {
							for (CartOrderProductDetail copd : cop.getDetails()) {
								if (copd.getProdId().equals(addonPdId)) {
									// 檢查庫存
									SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql,
											new Object[] { copd.getProdSpecId() }, 0, 1)[0];
									Integer inventory = si.getInventory();
									// do something
									if (inventory <= 0) {
										// 庫存不足
										cartMessage += "庫存不足無法購買！";
										copd.setQty(0);
									} else if (inventory < Integer.parseInt(qty)) {
										// 庫存量少於所選數量
										cartMessage += "庫存数量不足于所选的数量，已调整为：" + inventory;
										copd.setQty(inventory);
									} else {
										copd.setQty(Integer.parseInt(qty));
									}
									break;
								}
							}
						} else {
							// 主商品更改數量，prodSpecId要一併傳回
							if (qty != null) {
								Integer selectProdQty = Integer.parseInt(qty);
								// 檢查庫存
								CartOrderProduct copCurrent = (CartOrderProduct) baseMgr.get(CartOrderProduct.class,
										cop.getCartOrderProdId());
								SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql,
										new Object[] { copCurrent.getProdSpecId() }, 0, 1)[0];
								Integer inventory = si.getInventory();
								if (inventory <= 0) {
									cartMessage += "所选属性库存不足";
								} else {
									if (selectProdQty > inventory) {
										// 庫存量少於所選數量
										cartMessage += "库存不足";// ，已调整为：" + inventory;
										// cop.setProdSpecId(specCode);
										// cop.setQty(inventory);
									} else {
										cop.setQty(selectProdQty);
									}
									cartMessage += updateCartDetail(cop, copCurrent);

								}
							} else {
								// 主商品更改屬性

								// 檢查庫存
								CartOrderProduct copCurrent = (CartOrderProduct) baseMgr.get(CartOrderProduct.class,
										Long.valueOf(productid));
								SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql, new Object[] { specCode },
										0, 1)[0];
								Integer inventory = si.getInventory();

								if (inventory <= 0) {
									cartMessage += "所选属性库存不足";
								} else {
									if (cop.getQty() > inventory) {
										// 庫存量少於所選數量
										cartMessage += "所选属性数量不足于所选的数量";// ，已调整为：" + inventory;
										// cop.setProdSpecId(specCode);
										// cop.setProdSpecName(si.getSpecification().getSpecificationName());
										// cop.setQty(inventory);
									} else {
										cop.setProdSpecId(specCode);
										cop.setProdSpecName(si.getSpecification().getSpecificationName());
									}

									cartMessage += updateCartDetail(cop, copCurrent);

								}
							}
						}
						break;
					}
				}
				if (!cartMessage.equals("")) {
					throw new YekMobileException(cartMessage);
				}
				cartOrdersService.update(cartOrders);
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				cartOrders = cartOrdersService.calculateCart(cartOrders, optional);
			}

			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));

			// 產生XML
			Document document = DocumentHelper.createDocument();
			document.addElement("dataset");

			this.createSuccessResult(document, "新增项目成功");

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.addCart error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.addCart error :{}", e.toString());
			this.createErrorResult("提交失败", "提交数据有误");
		}

		return "finish";
	}

	/**
	 * 14.删除购物车商品接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String delCart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();

			String productid = request.getParameter("productid");
			String productspecid = request.getParameter("productspecid");
			String cartid = request.getParameter("cartid");

			CartOrders cart = cartOrdersService.get(cartid + "_yekmobile");
			if (!cart.getMemberId().equals(memberId)) {
				throw new YekMobileException("登入讯息有误");
			}

			for (CartOrderProduct cop : cart.getCartOrderProducts()) {
				if (cop.getProdId().equals(productid) && cop.getProdSpecId().equals(productspecid)) {
					if (!cop.getProdId().equals(productid)) {
						continue;
					}
					for (CartOrderProductDetail copd : cop.getDetails()) {
						baseMgr.delete(copd);
					}
					baseMgr.delete(cop);
				}
			}
			Map<String, String> optional = new HashMap<String, String>();
			optional.put("domain", request.getServerName());
			optional.put("cookie", userData.getApplySource());
			CartOrders cartOrders = cartOrdersService.calculateCart(cart, optional);
			// 记录购物车商品数量
			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));

			// 產生XML
			Document document = DocumentHelper.createDocument();
			document.addElement("dataset");

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.delCart error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.delCart error :{}", e.toString());
			this.createErrorResult("提交失敗", "提交数据有误");
		}

		return "finish";
	}

	/**
	 * 15.获取收藏盒列表教口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String golistWish() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			// String memberId = "0000763652";

			CommonCriteria crit = new CommonCriteria();
			crit.addEq("memberId", memberId);
			crit.addEq("categoryId", null);
			crit.addNe("shelfPrice", null);
			crit.addNe("is_delete", "Y");
			List<ViewWishList> list = memberService.getViewWishLists(0, -1, crit, null);

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			for (ViewWishList w : list) {
				Element x_wishlist = x_dataset.addElement("wishlist");
				x_wishlist.addElement("wishlistid").setText(String.valueOf(w.getId()));
				x_wishlist.addElement("productid").setText(w.getProductId());
				x_wishlist.addElement("productname").setText(w.getProductName());
				x_wishlist.addElement("putproductprice").setText(formatToString(w.getShelfPrice()));

				crit = new CommonCriteria();
				crit.addEq("productId", w.getProductId());
				crit.addEq("type", "MAIN");
				crit.addEq("isDelete", "N");
				List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
				int b1 = 0;
				for (Image img : images) {
					if (img.getImgFilePath().indexOf("_m75") != -1) {
						x_wishlist.addElement("image_path").setText(img.getImgFilePath());
						b1 = 1;
						break;
					}
				}
				if (b1 == 0) {
					x_wishlist.addElement("image_path").addText("");
				}
			}

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistWish error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistWish error :{}", e.toString());
			this.createErrorResult("提交失败", "提交数据有误");
		}

		return "finish";
	}

	/**
	 * 16.提交商品至收藏盒接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addWish() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			// String memberId = "0000763652";

			String productid = request.getParameter("productid");
			String productprice = request.getParameter("productprice");

			WishList entity = new WishList();
			entity.setMemberId(memberId);
			entity.setProductId(productid);
			entity.setPutProductPrice(new BigDecimal(productprice));
			entity.setFullUrl(ServerValue.getFrontContextPath() + "/product/product.do?productId=" + productid);
			entity.setIsPriceNotify("N");
			entity.setIsRestockNotify("N");
			entity.setLowerPriceNotify(new BigDecimal("0.0"));
			if (memberService.checkWishListExist(entity)) {
				throw new YekMobileException("此商品已存在於收藏盒中");
			}
			this.memberService.saveWishList(entity);

			// 產生XML
			Document document = DocumentHelper.createDocument();
			document.addElement("dataset");

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.addWish error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.addWish error :{}", e.toString());
			this.createErrorResult("提交失敗", "提交收藏盒数据有误");
		}

		return "finish";
	}

	/**
	 * 17.删除收藏盒商品接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String delWish() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			// String memberId = userData.getMemberId();
			// String memberId = "0000763652";

			String wishlistid = request.getParameter("wishlistid");

			String[] delList = wishlistid.split(",");
			memberService.deleteWishList(delList);

			// 產生XML
			Document document = DocumentHelper.createDocument();
			document.addElement("dataset");

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.delWish error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.delWish error :{}", e.toString());
			this.createErrorResult("提交失败", "提交收藏盒数据有误");
		}

		return "finish";
	}

	/**
	 * 18.获取最新快报列表接口
	 * 
	 * @return 最新快报列表
	 * @throws Exception
	 */
	public String listNewsAll() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			List<Announcement> list = announcementService.getAll(0, -1, new String[] { "startDate desc",
					AnnouncementService.SHOW_SEQ_SORT_CLAUSE, "modifyDate desc" });

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			for (Announcement ann : list) {
				Element x_news = x_dataset.addElement("news");
				x_news.addElement("nid").setText(ann.getId().toString());
				x_news.addElement("subject").setText(ann.getSubject());
				x_news.addElement("body").setText(StringUtils.defaultString(ann.getBody(), ""));
				x_news.addElement("createdate").setText(
						DateUtil.convertDateToString(EcConstant.PATTERN_DATE, ann.getCreateDate()));
				x_news.addElement("startdate").setText(
						DateUtil.convertDateToString(EcConstant.PATTERN_DATE, ann.getStartDate()));
				x_news.addElement("enddate").setText(DateUtil.convertDateToString(EcConstant.PATTERN_DATE, ann.getEndDate()));
			}
			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.listNewsAll error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.listNewsAll error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误，可能是网路有问题");
		}

		return "finish";
	}

	/**
	 * 19.获取最新快报接口
	 * 
	 * @return 最新快报
	 * @throws Exception
	 */
	public String getNews() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String newsid = request.getParameter("newsid");
		try {
			Announcement ann = announcementService.getVisibleAnnouncementById(newsid);

			if (ann == null) {
				throw new YekMobileException("最新快报不存在或是已过期");
			}

			if (!StringUtils.equalsIgnoreCase(ann.getIsDelete(), "N")) {
				throw new YekMobileException("最新快报(id:" + newsid + ")已删除");
			}

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			Element x_news = x_dataset.addElement("news");
			x_news.addElement("nid").setText(ann.getId().toString());
			x_news.addElement("subject").setText(ann.getSubject());
			x_news.addElement("body").addCDATA(StringUtils.defaultString(ann.getBody(), "")); // edit by Andy Chiang
			x_news.addElement("createdate").setText(
					DateUtil.convertDateToString(EcConstant.PATTERN_DATE, ann.getCreateDate()));
			x_news.addElement("startdate").setText(DateUtil.convertDateToString(EcConstant.PATTERN_DATE, ann.getStartDate()));
			x_news.addElement("enddate").setText(DateUtil.convertDateToString(EcConstant.PATTERN_DATE, ann.getEndDate()));

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getNews error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getNews error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误，可能是网路有问题");
		}

		return "finish";
	}

	/**
	 * 20.获取寄送地理位置接口(省份,城市,区)
	 * 
	 * @return 地理讯息
	 * @throws Exception
	 */
	public String getgeoinfo() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String geotype = request.getParameter("geotype");
		String geoid = request.getParameter("geoid");
		String cartid = request.getParameter("shopcartid");
		try {
			// TODO 直接购买没有cartid!!
			if (StringUtils.isBlank(cartid)) {
				throw new YekMobileException("参数错误");
			}

			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}
			// cartid = memberId; // TODO test
			CartOrders cartOrders = cartordersService.getCart(memberId, cartid + "_yekmobile");
			if (memberId.equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			}
			Document document = null;
			if (StringUtils.equals(geotype, "1")) {
				Map<String, String> provincesMap = deliveryRuleService.getCartProvinces(cartOrders.getCartId());

				document = DocumentHelper.createDocument();
				Element x_dataset = document.addElement("dataset");
				x_dataset.addElement("geotype").setText(geotype);

				Iterator<String> keyIter = provincesMap.keySet().iterator();
				while (keyIter.hasNext()) {
					String name = keyIter.next();
					// String code = provincesMap.get(name);

					Element geoInfo = x_dataset.addElement("geo_info");
					geoInfo.addElement("geo_code").setText(name);
					geoInfo.addElement("geo_name").setText(name);
				}
				this.createSuccessResult(document);
			} else if (StringUtils.equals(geotype, "2") && StringUtils.isNotBlank(geoid)) {
				Map<String, String> cityMap = deliveryRuleService.getMobileCartCitys(cartid, geoid);

				document = DocumentHelper.createDocument();
				Element x_dataset = document.addElement("dataset");
				x_dataset.addElement("geotype").setText(geotype);

				Iterator<String> keyIter = cityMap.keySet().iterator();
				while (keyIter.hasNext()) {
					String name = keyIter.next();
					// String code = cityMap.get(name);

					Element geoInfo = x_dataset.addElement("geo_info");
					geoInfo.addElement("geo_code").setText(name);
					geoInfo.addElement("geo_name").setText(name);
				}
				this.createSuccessResult(document);

			} else if (StringUtils.equals(geotype, "3") && StringUtils.isNotBlank(geoid)) {
				List<ViewDeliveryRule> districts = deliveryRuleService.getCartDistricts(cartid, geoid);

				document = DocumentHelper.createDocument();
				Element x_dataset = document.addElement("dataset");

				x_dataset.addElement("geotype").setText(geotype);

				for (ViewDeliveryRule district : districts) {
					Element geoInfo = x_dataset.addElement("geo_info");
					geoInfo.addElement("geo_code").setText(district.getToDistrict());
					geoInfo.addElement("geo_name").setText(district.getToDistrict());
				}
				this.createSuccessResult(document);
			} else {
				throw new YekMobileException("地理讯息型态或地理ID代码不存在");
			}

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getgeoinfo error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getgeoinfo error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误，可能是网路有问题");
		}

		return "finish";
	}

	/**
	 * 21.执行购物车结帐作业接口(COD)
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkoutcart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			// Member member = memberService.get(userData.getMemberId());
			String Source_ID = StringUtils.defaultString(request.getParameter("Source_ID"));
			applySource = "yek_mobile_cart_" + Source_ID;
			Orders order = setUpOrder(request, userData, null);
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			Element x_order = x_dataset.addElement("order");
			x_order.addElement("order_id").setText(order.getOrderId());
			x_order.addElement("order_price").setText("" + order.getMustPay().floatValue());
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.checkoutcart error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.checkoutcart error :{}", e.toString());
			this.createErrorResult("提交失败", "获取数据有误，可能是网路有问题");
		}

		return "finish";
	}

	private String applySource = "yekmobile";

	/**
	 * 22.执行直接结帐作业接口(COD)
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkoutdirect() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}
			// Member member = memberService.get(userData.getMemberId());
			CartOrders cartOrders = createBuyNowCart(request, userData);
			String Source_ID = StringUtils.defaultString(request.getParameter("Source_ID"));
			applySource = "yek_mobile_dirt_" + Source_ID;
			Orders order = setUpOrder(request, userData, cartOrders.getCartId());

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			Element x_order = x_dataset.addElement("order");
			x_order.addElement("order_id").setText(order.getOrderId());
			x_order.addElement("order_price").setText("" + order.getMustPay().floatValue());
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.checkoutdirect error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.checkoutdirect error :{}", e.toString());
			this.createErrorResult("提交失败", "获取数据有误，可能是网路有问题");
		}

		return "finish";
	}

	private String currentCartId; // 购物车
	private String productid; // 商品ID
	private String productspecid; // 商品规格属性ID
	private String addonProductid; // 加购商品ID
	private String addonProductspecid; // 加购商品规格属性ID
	private String npmProductid; // 任购商品ID
	private String npmProductspecid; // 任购商品规格属性ID
	private String amount; // 商品数量
	private String username; // 客户姓名
	private String provice; // 寄送省份
	private String city; // 寄送城市
	private String district; // 寄送区域
	private String zipCode; // 邮编
	private String address; // 街道地址
	private String codtype; // COD型态
	private String paymentTp;
	private String telArea; // 电话区码
	private String tel; // 电话
	private String telExt; // 分机
	private String mobile; // 电话
	private String invoice; // invoice 讯息
	private String bonus; // 购物金底扣金额
	private String couponInfo; // 使用之礼券ID
	private String vrtBlnc;
	private String giftCard;
	private String addressed;// 地址簿ID

	private Orders setUpOrder(HttpServletRequest request, UserData userData, String cartId) throws Exception {
		Orders order = null;
		String rsPage = "";
		String memberId = userData.getMemberId();
		if (cartId != null && cartId.length() > 0) {
			rsPage = "buy";
			currentCartId = cartId;
		} else {
			rsPage = "cart";
			currentCartId = memberId + "_yekmobile";
		}
		productid = StringUtils.defaultString(request.getParameter("productid"));
		productspecid = StringUtils.defaultString(request.getParameter("productspecid"));
		addonProductid = StringUtils.defaultString(request.getParameter("addonProductid"));
		addonProductspecid = StringUtils.defaultString(request.getParameter("addonProductspecid"));
		npmProductid = StringUtils.defaultString(request.getParameter("npmProductid"));
		npmProductspecid = StringUtils.defaultString(request.getParameter("npmProductspecid"));
		amount = StringUtils.defaultString(request.getParameter("amount"));
		addressed = StringUtils.defaultString(request.getParameter("addressed"));
		if (false == deliveryRuleService.chkProdDetailCanUseCod("cart", currentCartId)) {
			throw new YekMobileException("此购物车商品不能使用货到付款");
		}
		AddressBook ab = memberService.getAddressBook(Long.parseLong(addressed));
		if (null == ab) {
			throw new YekMobileException("无此地址簿");
		}
		username = StringUtils.defaultString(ab.getContactName());
		provice = StringUtils.defaultString(ab.getProvince());
		city = StringUtils.defaultString(ab.getCity());
		district = StringUtils.defaultString(ab.getDistrict());
		zipCode = StringUtils.defaultString(ab.getZipCode());
		address = StringUtils.defaultString(ab.getAddr());
		telArea = StringUtils.defaultString(ab.getAreaCode());
		tel = StringUtils.defaultString(ab.getPhone());
		telExt = StringUtils.defaultString(ab.getExtension());
		mobile = StringUtils.defaultString(ab.getMobile());
		if (mobile.isEmpty() || provice.isEmpty() || city.isEmpty() || district.isEmpty() || address.isEmpty()
				|| zipCode.isEmpty()) {
			throw new YekMobileException("地址簿资料不完整，无法成立订单");
		}

		codtype = StringUtils.defaultString(request.getParameter("codtype"));
		paymentTp = "30";
		if (StringUtils.equalsIgnoreCase(codtype, "pos")) {
			paymentTp = "60";
		}
		DeliveryRule dr = null;
		if (codtype.equals("cash")) {
			dr = deliveryRuleService.getCartDeliveryRule(currentCartId, ab.getProvince(), ab.getCity(), ab.getDistrict(),
					"20");
		}
		if (codtype.equals("pos")) {
			dr = deliveryRuleService.getCartDeliveryRule(currentCartId, ab.getProvince(), ab.getCity(), ab.getDistrict(),
					"30");
		}
		if (null == dr) {
			throw new YekMobileException("此地址不符合货到付款地址");
		}
		invoice = StringUtils.defaultString(request.getParameter("invoice"));
		bonus = StringUtils.defaultString(request.getParameter("bonus"));
		couponInfo = StringUtils.defaultString(request.getParameter("coupon_ID"));
		// no myWallet & giftCard
		vrtBlnc = "0.00";
		giftCard = "0.00";
		if (StringUtils.isNotBlank(currentCartId)) {
			// 手机无判断验证码是否正确
			CartOrders cartOrders = cartordersService.getCart(memberId, currentCartId);
			if (memberId.equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			}
			if (StringUtils.equalsIgnoreCase("single", ServerValue.getDiscountType())) {
				if (new BigDecimal(bonus).compareTo(BigDecimal.ZERO) == 1 && couponInfo.length() > 0) {
					throw new YekMobileException("礼券或购物金，请择一使用");
				}
			}
			try {
				// 取得client ip
				String host = request.getHeader("X-Forwarded-For");
				if (StringUtils.isBlank(host)) {
					host = StringUtils.defaultString(request.getRemoteAddr(), "0.0.0.0");
				} else if (host.length() > 100) {
					host = host.substring(0, 100);
				}
				// 取得channel id
				int chId = 0;
				cartOrders.setChannelSeq(chId);
				// 手机无达夫妮门店
				if (StringUtils.isNotBlank(username)) {
					StringBuffer sbReceiver = new StringBuffer();
					sbReceiver.append(StringUtils.defaultString(username)).append(",");
					sbReceiver.append(StringUtils.defaultString(telArea)).append(",");
					sbReceiver.append(StringUtils.defaultString(tel)).append(",");
					sbReceiver.append(StringUtils.defaultString(telExt)).append(",");
					sbReceiver.append(StringUtils.defaultString(mobile));
					userData.writeRawValue("receiverData", new String(Base64.encode(sbReceiver.toString().getBytes())));
				}

				// 检验是否能购买
				String tlpId = timeLimitSaleService.canBuy(cartOrders.getCartOrderProducts(), memberId);
				if (!"2".equals(tlpId)) {
					throw new Exception();
				}

				// 訂購流程_商品&赠品不足之检查
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", applySource);
				optional.put("rsPage", rsPage);
				for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
					if ("6".equals(cop.getProdTp())) {
						throw new YekMobileException("MOBILE.ORDER.NO.NM");
					}
				}
				String invntryInfo = cartordersService.checkSpecInventory(currentCartId, "", optional, "step2");
				if (!"OK".equals(invntryInfo)) {
					List<CartOrderProductDetail> cartOrderProductDetailList = new ArrayList<CartOrderProductDetail>();
					for (CartOrderProduct cop : cartOrders.getCartOrderProducts()) {
						cartOrderProductDetailList.addAll(cop.getDetails());
					}

					for (CartOrderProductDetail copd_ : cartOrderProductDetailList) {

						SpecificationInventory specificationInventory = new SpecificationInventory();
						CommonCriteria criteria = new CommonCriteria();
						criteria.addEq("productId", copd_.getProdId());
						criteria.addEq("specId", Long.parseLong(copd_.getProdSpecId()));
						specificationInventory = productService.getSpecificationInventory(copd_.getProdId(),
								Long.parseLong(copd_.getProdSpecId()));
						int availableInventory = specificationInventory.getInventory();
						Specification spec = (Specification) baseMgr.get(Specification.class, Long.valueOf(copd_.getProdSpecId()));
						// 找主商品的购物车数量
						CartOrderProduct cop = (CartOrderProduct) baseMgr.get(CartOrderProduct.class, copd_.getCartOrderProdId());
						if (copd_.getDetailTp().equals("2") && null == copd_.getCartOrderProdId()) {// 活动赠品
							if (availableInventory < copd_.getQty()) {
								baseMgr.executeHql("update CartOrderProductDetail set qty =? where cartOrderDetailId=?", new Object[] {
										availableInventory, copd_.getCartOrderDetailId() });
							} else if (availableInventory <= 0) {
								baseMgr.executeHql("delete from CartOrderProductDetail where cartOrderDetailId=?",
										new Object[] { copd_.getCartOrderDetailId() });
							}
						} else if ("2".equals(copd_.getDetailTp())) {
							if (copd_.getQty() > cop.getQty()) {
								baseMgr.executeHql("update CartOrderProductDetail set qty =? where cartOrderDetailId=?", new Object[] {
										cop.getQty(), copd_.getCartOrderDetailId() });
							} else if (availableInventory < copd_.getQty()) {
								baseMgr.executeHql("update CartOrderProductDetail set qty =? where cartOrderDetailId=?", new Object[] {
										availableInventory, copd_.getCartOrderDetailId() });
							} else if (availableInventory <= 0) {
								baseMgr.executeHql("delete from CartOrderProductDetail where cartOrderDetailId=?",
										new Object[] { copd_.getCartOrderDetailId() });
							}
						}
						cartOrders = cartordersService.getCart(memberId, currentCartId);
					}
				}
				// 本次无信用卡

				if (StringUtils.isBlank(invoice)) {
					cartOrders.setInvoiceTp("01");
				} else {
					cartOrders.setInvoiceTp("02");
				}
				cartOrders.setInvoiceTitle(invoice);
				// 本次无信用卡 & 达夫妮
				order = pay(cartOrders, host, applySource, "", "", "");
			} catch (Exception e) {
				if ("MOBILE.ORDER.NO.NM".equals(e.getMessage())) {
					throw new YekMobileException("手机订单不能有任选商品");
				} else if ("BAD.ORDER.CHECK".equals(e.getMessage())) {
					throw new YekMobileException("订单审核未过，请连络客服。");
				} else {
					throw new YekMobileException("数量不足或资料错误");
				}
			}
		}
		return order;
	}

	private Orders pay(CartOrders cartOrders, String host, String channel, String storeId, String creditcardDetailId,
			String period) throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		Map addonInfo = new HashMap();
		String cpProductId = "";
		String cpUUID = "";
		boolean duplCouponProduct = false;
		if (StringUtils.isNotBlank(couponInfo)) {
			String[] dealCoupon = couponInfo.split(",");
			BigDecimal bcCoupon = BigDecimal.ZERO;
			for (int icp = 0; icp < dealCoupon.length; icp++) {
				String[] processCoupon = dealCoupon[icp].split("/");
				bcCoupon = bcCoupon.add(new BigDecimal(processCoupon[2].toString()));
			}
			cartOrders.setCoupon(bcCoupon);
		}
		if (couponInfo != null && couponInfo.length() > 0) {
			addonInfo.put("coupon", couponInfo);
		}
		addonInfo.put("remoteAddr", host);
		addonInfo.put("applySource", channel);
		addonInfo.put("promoteProduct", "");
		addonInfo.put("domain", request.getServerName());
		addonInfo.put("channelChild", userData.getChChildCookie());
		addonInfo.put("storeId", storeId);

		String userAgent = request.getHeader("User-Agent");
		String bcookie = request.getHeader("Cookie");
		Map requestMap = request.getParameterMap();
		addonInfo.put("userAgent", userAgent);
		addonInfo.put("bcookie", bcookie);
		addonInfo.put("requestMap", JSONUtil.serialize(requestMap));
		// for mobile channel
		// 兩個接口傳入Source_ID這參數，這會帶入渠道的代碼(這代碼會由廠商自行定義，最長不會超過30的字元)，如果是超過30字元請切截數據。
		if (channel.length() > 30) {
			channel = channel.substring(0, 30);
		}
		cartOrders.setChannel(channel);
		if (address.length() > 100) {
			address = address.substring(0, 100);
		}
		if (true == isInteger2(address)) {
			throw new CartException("不允许全部数字输入！");
		}
		cartOrders.setReceiverAddr(address);
		// if ("※".equals(district.split(",")[0].substring(0, 1))) {
		// district = district.split(",")[0].substring(1);
		// } else {
		// district = district.split(",")[0];
		// }
		cartOrders.setReceiverArea(district);
		cartOrders.setReceiverCity(city);
		cartOrders.setReceiverExt(telExt);
		cartOrders.setReceiverMobile(mobile);

		if (true == isInteger(username)) {
			throw new CartException("不允许数字输入！");
		}
		cartOrders.setReceiverName(username);
		cartOrders.setReceiverPhone(tel);
		cartOrders.setReceiverPhoneArea(telArea);
		cartOrders.setReceiverProvince(provice);
		cartOrders.setMemo("");
		if (zipCode.length() > 6) {
			zipCode = zipCode.substring(0, 6);
		}
		cartOrders.setReceiverZip(zipCode);
		String memberId = StringUtils.defaultString(userData.getMemberId());
		Member member = memberService.get(memberId);
		// 页无此流程
		// if ("xx".equals(member.getSendEmail())) {
		// cartOrders.setReceiverEmail(mail);
		// }

		// 目前只有cod，不允许拆单
		// 是否允许拆单
		// if (cartOrders.getCartOrderProducts().size() > 1 && "Y".equals(allowSplit)) {
		// cartOrders.setAllowSplit("Y");
		// } else {
		// cartOrders.setAllowSplit("N");
		// }

		Map payment = new HashMap();
		payment.put("paymentType", paymentTp);
		payment.put("vrtBlnc", vrtBlnc);
		payment.put("giftCard", giftCard);
		payment.put("bonus", bonus);
		payment.put("creditcardDetailId", creditcardDetailId);
		payment.put("period", period);
		if ("02".equals(cartOrders.getInvoiceTp())) {
			payment.put("invotype", cartOrders.getInvoiceTp());
			payment.put("invoTitle", cartOrders.getInvoiceTitle());
		}
		List<String> campaignList = new ArrayList<String>();
		Map<String, ApplyCampaign> acm = cartOrders.getApplyCampaign();
		Iterator<String> iter = acm.keySet().iterator();
		while (iter.hasNext()) {
			campaignList.add(iter.next());
		}
		// if (null != reqMap) {
		// campaigns = campaigns;
		// }
		// String[] campaignSplit = campaigns.split(",");
		// for (String str : campaignSplit) {
		// campaignList.add(str);
		// }

		String hql = "from CampaignProduct where productId=?";
		// TODO: addCmpPdId
		Object[] cps = baseMgr.queryByHql(hql, new Object[] { "" }, 0, 1);
		if (cps != null && cps.length > 0) {
			CampaignProduct cp = (CampaignProduct) cps[0];
			cartOrders = cartordersService.addPromoteProduct(cartOrders, cp.getUuid(), "5");

		}
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", userData.getApplySource());
		cartOrders = cartordersService.calculateCart(cartOrders, optional, campaignList);
		// 订单成立时应只允许isDelete = 'N' 或 'H' 才能写入订单。
		Product productNH;
		for (CartOrderProduct cartOrderProd : cartOrders.getCartOrderProducts()) {
			productNH = productService.get(cartOrderProd.getProdId());
			if ("F".equals(productNH.getIsDelete()) || "Y".equals(productNH.getIsDelete())
					|| "Q".equals(productNH.getIsDelete())) {
				logger.error("商品销售状态不符, cartId:{}, cart product:{}, product:{}", new Object[] { cartOrders.getCartId(),
						cartOrderProd, productNH });
				throw new CartException("商品销售状态不符！");
			}
		}
		// editTotalAmount = editTotalAmount.substring(0, editTotalAmount.indexOf(".") + 2);
		// // System.out.println(finalTotalAmount);
		// BigDecimal amountFromPage = new BigDecimal((editTotalAmount));
		BigDecimal cartSumAmount = cartOrders.getAmount().add(cartOrders.getDiscount());

		// 購物金檢查-会员是否有购物金
		Balance balance = member.getBalance();
		if (new BigDecimal(bonus).compareTo(balance.getBonusBalance()) == 1) {
			logger.error("cart.id:{}, 折抵购物金>会员购物金, editBonus:{}. balance:{}", new Object[] { cartOrders.getCartId(), bonus,
					balance.getBonusBalance() });
			throw new CartException("折抵购物金>会员购物金！");
		}
		BonusSetting bonusSetting = bonusSettingService.getLowestDiscount(cartSumAmount);
		if (null == bonusSetting) {
			bonusSetting = new BonusSetting();
			bonusSetting.setDiscountLimit(BigDecimal.valueOf(200));
			bonusSetting.setPercentage(BigDecimal.valueOf(10));
		}
		BigDecimal perc = bonusSetting.getPercentage();
		perc = perc.divide(BigDecimal.valueOf(100));
		BigDecimal iOffset = cartSumAmount;
		iOffset = iOffset.add(cartOrders.getShipfare());
		if ("30".equals(paymentTp) || "60".equals(paymentTp)) {
			iOffset = iOffset.add(addressService.getCodFee());
		}
		iOffset = iOffset.subtract(cartOrders.getDiscount());
		if (StringUtils.isNotBlank(couponInfo) && couponInfo.length() > 0) {
			iOffset = iOffset.subtract(cartOrders.getCoupon());
		}
		iOffset = iOffset.multiply(perc).setScale(0, RoundingMode.DOWN);
		if (iOffset.compareTo(bonusSetting.getDiscountLimit()) == 1 && bonusSetting.getDiscountLimit().intValue() > 0) {
			iOffset = bonusSetting.getDiscountLimit();
		}
		// 購物金檢查-折抵购物金與实际折抵购物金 不可差異大于1
		BigDecimal pageBonus = new BigDecimal(bonus);
		if (iOffset.subtract(pageBonus).floatValue() < -1.0) {
			logger.error("cart.id:{}, 折抵购物金>实际折抵购物金, iOffset:{}. editBonus:{}", new Object[] { cartOrders.getCartId(),
					iOffset, bonus });
			throw new CartException("折抵积分>实际折抵积分！");
		}
		// 账户余额检查chkVrtBlnc
		// if (new BigDecimal(vrtBlnc).compareTo(member.getBalance().getVirtualBalance()) == 1) {
		// logger.error("cart.id:{}, 我的账户余额>实际我的账户余额,chkVrtBlnc:{}, memberVirtualBalance: {}", new Object[] {
		// cartOrders.getCartId(), vrtBlnc, member.getBalance().getVirtualBalance() });
		// throw new CartException("我的账户余额>实际我的账户余额！");
		// }
		// 礼品卡余额检查chkGiftCard
		// if (new BigDecimal(giftCard).compareTo(member.getBalance().getGiftcardBalance()) == 1) {
		// logger.error("cart.id:{}, 我的礼品卡余额>实际我的礼品卡余额,chkGiftCard:{}, memberGiftCardBalance: {}", new Object[] {
		// cartOrders.getCartId(), giftCard, member.getBalance().getGiftcardBalance() });
		// throw new CartException("我的礼品卡余额>实际我的礼品卡余额！");
		// }
		// 剩余应付金额不可为负值
		BigDecimal totalAmount = cartOrders.getAmount().add(cartOrders.getDiscount());

		if (totalAmount.compareTo(BigDecimal.ZERO) == -1) {
			logger.error("cart.id:{}, 剩余应付金额<,editTotalAmount:{}", totalAmount);
			throw new CartException("剩余应付金额<0！");
		}
		if (cartOrders.getCartOrderProducts() == null || cartOrders.getCartOrderProducts().size() == 0) {
			// || Math.abs(cartSumAmount.subtract(amountFromPage).floatValue()) != 0) {
			logger.error("cart:{}, cart products:{}, cart.sum:{}",
					new Object[] { cartOrders, cartOrders.getCartOrderProducts(), cartSumAmount });
			// cartOrders.getCartOrderProducts(), cartSumAmount, amountFromPage });
			throw new CartException("订单金额与预期不符，请检查购物车！");
		}
		// 手机验证
		if ("on".equals(ServerValue.getBlockOrderPaymentType())) {
			if ("10".equals(paymentTp) || "20".equals(paymentTp) || "30".equals(paymentTp) || "60".equals(paymentTp)) {
				if ("nonmember".equals(member.getApplySource())) {
					throw new CartException("会员功能限耀点100会员使用");
				}
				if (member.getIsMobileMember() == false) {
					throw new CartException("手机验证錯誤");
				}
			}
		}
		// 惡意訂購不允許使用COD付款
		if (!"true".equals(memberService.badOrderCheck(member.getMemberId(), cartOrders.getReceiverAddr(),
				cartOrders.getReceiverMobile(), cartOrders.getReceiverPhone()))) {
			throw new CartException("BAD.ORDER.CHECK");
		}
		Orders result = null;
		boolean retry = true;
		int count = 0;
		do {
			try {
				count++;
				result = orderService.createOrderWithPay(cartOrders, addonInfo, payment);
				retry = false;
				// 刪除購物車
				cartordersService.cleanCartOrderNow(cartOrders.getCartId());
			} catch (Exception e) {
				logger.error("fail " + count + " times, cart:" + cartOrders, e);
				Thread.sleep(100);
				CartOrders tmp = cartordersService.getCart(cartOrders.getMemberId(), cartOrders.getCartId());
				if (tmp == null || !tmp.getModifyDate().equals(cartOrders.getModifyDate())
						|| "error.coupon.isused".equals(e.getMessage())) {
					throw new CartException("订单已经建立，请检查最近订单明细！");
				} else if ("errors.order.address.not.match".equals(e.getMessage())) {
					throw new CartException("地址资料不符合！");
				} else if ("errors.order.badman".equals(e.getMessage())) {
					throw new CartException("您的帐号异常, 请洽客服人员");
				} else if (e.getMessage() != null
						&& (e.getMessage().startsWith("error.coupon.") || e.getMessage().startsWith("error.order.") || e
								.getMessage().startsWith("error.payment."))) {
					// 丟這幾個開頭, 都是資料異常, 可以考慮丟到黑名單
					throw new CartException("订单建立失败！");
				} else if (e.getMessage().startsWith("订单毛利率不符合")) {
					String mailBody = e.getMessage().split("＠")[1];
					if (StringUtils.isNotBlank(mailBody)) {
						Mail mail = new Mail("订单防火墙通知信-前台订购", e.getMessage().split("＠")[1], systemValueMenu.getOptions()
								.get("fw_mail").getMemo1(), "");
						mail.setBcc("feeling.wang@yaodian100.com");
						mailService.save(mail);
					}
					if (tmp.getCartId().equals(tmp.getMemberId())) {
						throw new CartException("抱歉<br>请重新选购!,cart");
					} else {
						throw new CartException("抱歉<br>请重新选购!,buy");
					}
				} else if (count > 4) {
					throw new CartException("订单建立失败，请检查购物车！");
				}
			}
		} while (retry);
		return result;
		// return null;

	}

	// check addr
	public boolean isInteger2(String input) {
		try {
			Integer.parseInt(input);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	// check contactName
	public boolean isInteger(String input) {
		try {
			Integer.parseInt(input);
			if (input.matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	private CartOrders createBuyNowCart(HttpServletRequest request, UserData userData) throws Exception {
		String memberId = userData.getMemberId();
		String productid = request.getParameter("productid");
		String[] prodIds = null;
		if (StringUtils.isNotBlank(productid)) {
			prodIds = productid.split(",");
		}

		String qty = request.getParameter("amount");
		String npmProductid = request.getParameter("npmProductid");
		List<String> nmProds = null;
		if (StringUtils.isNotBlank(npmProductid)) {
			// 此次不加入N選M商品
			// nmProds = Arrays.asList(npmProductid.split(","));
		}
		String addonProductid = request.getParameter("addonProductid");
		List<String> addonProds = null;
		if (StringUtils.isNotBlank(addonProductid)) {
			// 此次不加入加購商品
			// addonProds = Arrays.asList(addonProductid.split(","));
		}
		String productspecid = request.getParameter("productspecid");
		List<String> specs = null;
		if (StringUtils.isNotBlank(productspecid)) {
			specs = Arrays.asList(productspecid.split("/"));
		}

		Product product = product2Service.get(prodIds[0]);

		CartOrders cartOrders = cartordersService.getCart(memberId, memberId + "_yekmobile");
		if (memberId.equals(cartOrders.getCartId())) {
			cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
		}
		// 取categoryId
		String cateId = product.getMainCategoryID() + "";
		String prodTp = product.getProductTypeStr();
		if ("6".equals(prodTp)) {
			cartOrders = cartordersService.createCart(memberId, prodIds[0], nmProds, NumberUtils.toLong(specs.get(0)),
					NumberUtils.toInt(qty), cateId, null);
		} else {
			cartOrders = cartordersService.createCart(memberId, prodIds[0], null, NumberUtils.toLong(specs.get(0)),
					NumberUtils.toInt(qty), cateId, addonProds);
		}
		Map<String, String> optional = new HashMap<String, String>();
		optional.put("domain", request.getServerName());
		optional.put("cookie", applySource);
		optional.put("rsPage", "buy");
		cartOrders = cartordersService.calculateCart(cartOrders, optional);

		String inventoryInfo = cartordersService.checkSpecInventory(cartOrders.getCartId(), "", optional, "step0Login");
		if (!StringUtils.equalsIgnoreCase(inventoryInfo, "OK")) {
			throw new YekMobileException("检查库存不合格");
		}
		return cartOrders;
	}

	/**
	 * 23.获取运费讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getlogisticprice() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			int freightBase = ServerValue.getFreightBase();
			x_dataset.addElement("free_limited").setText("" + freightBase);
			x_dataset.addElement("free_limited_unit").setText("kg");

			HashMap<String, Option> freightMap = addressService.getFreightMap();
			Iterator<String> keyIter = freightMap.keySet().iterator();
			while (keyIter.hasNext()) {
				String key = keyIter.next();
				Option option = freightMap.get(key);
				List<Province> provinces = addressService.getProvinceListByShipExpenseRank(key);
				for (Province province : provinces) {
					Element x_logist = x_dataset.addElement("logist_item");
					x_logist.addElement("province_id").setText(province.getId().toString());
					x_logist.addElement("province_name").setText(StringUtils.defaultIfEmpty(province.getName(), ""));
					x_logist.addElement("province_price").setText(StringUtils.defaultIfEmpty(option.getMemo1(), ""));
					x_logist.addElement("province_inc_price").setText(StringUtils.defaultIfEmpty(option.getMemo2(), ""));
				}
			}
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getlogisticprice error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getlogisticprice error :{}", e.toString());
			this.createErrorResult("提交失败", "提交结帐数据有误，电话号码格式有问题");
		}

		return "finish";
	}

	/**
	 * 24.获取可用之购物金与礼卷讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getavalbonus() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String catid = request.getParameter("catid");
		String productid = request.getParameter("productid");
		String addonproductid = request.getParameter("addonproductid");
		String npmproductid = request.getParameter("npmproductid");
		String cartid = request.getParameter("shopcartid");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			Member member = memberService.get(userData.getMemberId());
			List<CouponItem> couponitems = couponService.getItems(member.getMemberId());

			Balance myBalance = memberService.getBalance(userData.getMemberId());
			BigDecimal myBonus = myBalance.getBonusBalance();

			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			int couponitemIndex = 0;
			if (StringUtils.isNotBlank(productid) && StringUtils.isNotBlank(catid)) { // 直接购买
				Product product = productService.get(productid);
				// 购物金
				BigDecimal sumAmount = BigDecimal.ZERO;
				sumAmount = sumAmount.add(product.getPrpsShelfPrice());
				// n-m 金额在addon中都为-1，所以不做
				if (StringUtils.isNotBlank(addonproductid)) {
					String[] addonIds = addonproductid.split(",");
					Map<String, AddOnProduct> addonProds = product2Service.getAddOnProducts(product.getProductId(), false);
					for (String addonId : addonIds) {
						AddOnProduct addonProd = addonProds.get(addonId);
						if (addonProd == null) {
							throw new YekMobileException("主商品(id:" + productid + ")中无赠品或加购商品(id:" + addonId + ")");
						}
						sumAmount = sumAmount.add(addonProd.getAddOnPrice());
					}
				}
				// 購物金使用限制
				BonusSetting bonusSetting = null;
				if (null != bonusSettingService.getLowestDiscount(sumAmount)) {
					bonusSetting = bonusSettingService.getLowestDiscount(sumAmount);
				}
				BigDecimal bonus = BigDecimal.ZERO;
				if (null != bonusSetting) {
					bonus = sumAmount.multiply(bonusSetting.getPercentage()).divide(new BigDecimal(100));
				}
				if (myBonus.floatValue() < bonus.floatValue()) {
					bonus = myBonus;
				}
				x_dataset.addElement("bonus").setText("" + bonus.floatValue());

				// 礼卷
				if (couponitems.size() > 0) {
					for (CouponItem couponitem : couponitems) {
						Category cg = categoryService.get(Long.parseLong(catid));
						Shelf shelf = shelfService.getShelfByProductId(productid, DateUtil.getCurrentTime(),
								DateUtil.getCurrentTime());
						// 現行禮券規劃加入限額功能: 當商品售價 (unit_price) 超過設定之限額時, 才允許使用該禮券
						BigDecimal couponMinPrice = couponitems.get(couponitemIndex).getCoupon().getMinimumProductPrice();
						List<String> coupList = new ArrayList();
						if (couponService.isValid(couponitem, product.getProductId(), cg.getCategoryPath())) {
							if (null != couponMinPrice) {
								if (couponMinPrice.compareTo(shelf.getShelfPrice()) <= 0) {
									Element x_coupon = x_dataset.addElement("coupon");
									x_coupon.addElement("coupon_id").setText(couponitem.getCode());
									x_coupon.addElement("coupon_name").setText(couponitem.getCoupon().getName());
									x_coupon.addElement("productid").setText(productid);
									x_coupon.addElement("coupon_price").setText(couponitem.getCoupon().getFaceValue().toString());
								}
							}
						}
						couponitemIndex++;
					}
				}
			} else if (StringUtils.isNotBlank(cartid)) { // 购物车
				CartOrders cartOrders = cartordersService.getCart(memberId, cartid + "_yekmobile");
				if (memberId.equals(cartOrders.getCartId())) {
					cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
				}
				List<CartOrderProduct> cartOrderProductList = cartOrders.getCartOrderProducts();
				// 购物金
				BigDecimal cartSumAmount = cartOrders.getAmount().add(cartOrders.getDiscount());
				// 購物金使用限制
				BonusSetting bonusSetting = null;
				if (null != bonusSettingService.getLowestDiscount(cartSumAmount)) {
					bonusSetting = bonusSettingService.getLowestDiscount(cartSumAmount);
				}
				BigDecimal bonus = BigDecimal.ZERO;
				if (null != bonusSetting) {
					bonus = cartOrders.getAmount().multiply(bonusSetting.getPercentage()).divide(new BigDecimal(100));
				}
				if (myBonus.floatValue() < bonus.floatValue()) {
					bonus = myBonus;
				}
				x_dataset.addElement("bonus").setText("" + bonus.floatValue());

				// 礼卷
				if (couponitems.size() > 0 && cartOrderProductList.size() > 0) {
					for (CouponItem couponitem : couponitems) {
						StringBuilder sb = new StringBuilder();
						List<String> coupList = new ArrayList();
						for (CartOrderProduct cartorderProduct : cartOrderProductList) {
							Product product = productService.get(cartorderProduct.getProdId());
							Shelf shelf = shelfService.getShelfByProductId(cartorderProduct.getProdId(), DateUtil.getCurrentTime(),
									DateUtil.getCurrentTime());
							// 現行禮券規劃加入限額功能: 當商品售價 (unit_price) 超過設定之限額時, 才允許使用該禮券
							BigDecimal couponMinPrice = couponitems.get(couponitemIndex).getCoupon().getMinimumProductPrice();
							if (couponService.isValid(couponitem, cartorderProduct)) {
								if (null != couponMinPrice) {
									if (couponMinPrice.compareTo(shelf.getShelfPrice()) <= 0) {
										if (sb.length() > 0) {
											sb.append(",");
										}
										sb.append(cartorderProduct.getProdId());
									}
								}
							}
						}
						Element x_coupon = x_dataset.addElement("coupon");
						x_coupon.addElement("coupon_id").setText(couponitem.getCode());
						x_coupon.addElement("coupon_name").setText(couponitem.getCoupon().getName());
						x_coupon.addElement("productid").setText(sb.toString());
						x_coupon.addElement("coupon_name").setText("" + couponitem.getCoupon().getFaceValue().floatValue());

						couponitemIndex++;
					}
				}
			} else {
				throw new YekMobileException("传递参数不属于直接购买或购物车流程");
			}
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getavalbonus error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getavalbonus error :{}", e.toString());
			this.createErrorResult("获取失败", "weblogid有问题");
		}

		return "finish";
	}

	/**
	 * 25.获取订单列表接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getorder() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}
			Map<String, Object> content = gos.getMobileOrders(memberId);
			List<Orders> orders = (List<Orders>) content.get("orders");
			List<Orders> ordersH = (List<Orders>) content.get("ordersH");
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (Orders order : orders) {
				Element x_order = x_dataset.addElement("order");
				x_order.addElement("orderno").setText(order.getOrderId());
				x_order.addElement("orderdate").setText(df.format(order.getOrderDt()));
				// Element x_product = x_order.addElement("product");
				// List<OrderProduct> orderProducts = order.getOrderProduct();
				// for (OrderProduct orderProduct : orderProducts) {
				// x_product.addElement("productid").setText(orderProduct.getProdId());
				// x_product.addElement("productname").setText(orderProduct.getProdName());
				// }
				BigDecimal price = BigDecimal.ZERO;
				price = order.getTotalPrice().subtract(order.getBonus()).subtract(order.getCoupon()).add(order.getShipfare())
						.subtract(order.getDiscount()).add(order.getCodFee()).add(order.getInstallmentFee());
				x_order.addElement("price").setText("" + price.floatValue());
				x_order.addElement("paytype").setText(
						StringUtils.defaultIfEmpty(paymentTpMenu.getOptions().get(order.getPaymentTp()).getName(), ""));
				x_order.addElement("orderstatus_id").setText(StringUtils.defaultIfEmpty(order.getOrderSt(), ""));
				x_order.addElement("orderstatus").setText(
						StringUtils.defaultIfEmpty(orderStMenu.getOptions().get(order.getOrderSt()).getName(), ""));
				x_order.addElement("type_ID").setText("1");
				x_order.addElement("type").setText("最近");
			}
			for (Orders order : ordersH) {
				Element x_order = x_dataset.addElement("order");
				x_order.addElement("orderno").setText(order.getOrderId());
				x_order.addElement("orderdate").setText(df.format(order.getOrderDt()));
				// Element x_product = x_order.addElement("product");
				// List<OrderProduct> orderProducts = order.getOrderProduct();
				// for (OrderProduct orderProduct : orderProducts) {
				// x_product.addElement("productid").setText(orderProduct.getProdId());
				// x_product.addElement("productname").setText(orderProduct.getProdName());
				// }
				BigDecimal price = BigDecimal.ZERO;

				price = order.getTotalPrice().subtract(order.getBonus()).subtract(order.getCoupon()).add(order.getShipfare())
						.subtract(order.getDiscount()).add(order.getCodFee())
						.add(null == order.getInstallmentFee() ? BigDecimal.ZERO : order.getInstallmentFee());
				x_order.addElement("price").setText("" + price.floatValue());

				if (null == order.getPaymentTp()) {
					x_order.addElement("paytype").setText("");
				} else {
					if (null == paymentTpMenu.getOptions().get(order.getPaymentTp())) {
						x_order.addElement("paytype").setText("");
					} else {
						x_order.addElement("paytype").setText(
								StringUtils.defaultString(paymentTpMenu.getOptions().get(order.getPaymentTp()).getName()));
					}
				}
				x_order.addElement("orderstatus_id").setText(StringUtils.defaultIfEmpty(order.getOrderSt(), ""));
				x_order.addElement("orderstatus").setText(
						StringUtils.defaultIfEmpty(orderStMenu.getOptions().get(order.getOrderSt()).getName(), ""));
				x_order.addElement("type_ID").setText("2");
				x_order.addElement("type").setText("历史");
			}
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getorder error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(" e.toString():{}", e.toString());
			logger.info("YekMobileAction.getorder error :{}", e.toString());
			this.createErrorResult("获取失败", "weblogid有问题");
		}

		return "finish";
	}

	/**
	 * 26.获取详细订单讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getorderdetail() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}
		String orderId = request.getParameter("orderno");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			if (StringUtils.isBlank(orderId)) {
				throw new YekMobileException("传递参数不正确");
			}

			Orders order = orderService.getOrder(orderId);

			if (order == null) {
				throw new YekMobileException("订单不存在");
			}
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String imgUrl = "";
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			Element x_order = x_dataset.addElement("order");

			x_order.addElement("orderno").setText(order.getOrderId());
			x_order.addElement("orderdate").setText(df.format(order.getOrderDt()));

			Element x_products = x_order.addElement("products");
			List<OrderProduct> orderProducts = order.getOrderProduct();
			for (OrderProduct op : orderProducts) {
				Element x_product = x_products.addElement("product");
				x_product.addElement("productid").setText(op.getProdId());
				x_product.addElement("productname").setText(op.getProdName());
				x_product.addElement("producttype").setText(op.getProdTp());
				x_product.addElement("specid").setText(op.getProdSpecId());
				x_product.addElement("specname").setText(op.getProdSpecName());
				x_product.addElement("unitprice").setText("" + op.getUnitPrice().floatValue());
				x_product.addElement("amount").setText("" + op.getQty());
				imgUrl = ServerValue.getImgDomain() + "/PImg/" + op.getProdId().substring(0, 4) + "/" + op.getProdId() + "/"
						+ op.getProdId() + "_m135.jpg";
				x_product.addElement("productimaeurl").setText(imgUrl);
				if (StringUtils.equalsIgnoreCase(op.getProdTp(), "6")) {
					Element x_giftList = null;
					for (OrderProductDetail opd : op.getOrderProductDetail()) {
						if (StringUtils.equalsIgnoreCase(opd.getDetailTp(), "6")
								&& StringUtils.equalsIgnoreCase(op.getProdId(), opd.getProdId())) {
							if (x_giftList == null) {
								x_giftList = x_product.addElement("gift_list");
							}
							Element x_gift = x_giftList.addElement("gift");
							x_gift.addElement("gift_name").setText(opd.getProdName());
							x_gift.addElement("gift_product_id").setText("");
							x_gift.addElement("gift_spec_id").setText("");
						}
					}
				}
				if (StringUtils.equalsIgnoreCase(op.getProdTp(), "5")) {
					Element x_giftList = null;
					for (OrderProductDetail opd : op.getOrderProductDetail()) {
						if (StringUtils.equalsIgnoreCase(opd.getDetailTp(), "6")) {
							if (x_giftList == null) {
								x_giftList = x_product.addElement("gift_list");
							}
							Element x_gift = x_giftList.addElement("gift");
							x_gift.addElement("gift_name").setText(opd.getProdName());
							x_gift.addElement("gift_product_id").setText("");
							x_gift.addElement("gift_spec_id").setText("");
						}
					}
				}
				if (StringUtils.equalsIgnoreCase(op.getProdTp(), "0") || StringUtils.equalsIgnoreCase(op.getProdTp(), "1")
						|| StringUtils.equalsIgnoreCase(op.getProdTp(), "7")) {
					Element x_giftList = null;
					for (OrderProductDetail opd : op.getOrderProductDetail()) {
						if (StringUtils.equalsIgnoreCase(opd.getDetailTp(), "6")) {
							if (x_giftList == null) {
								x_giftList = x_product.addElement("gift_list");
							}
							Element x_gift = x_giftList.addElement("gift");
							x_gift.addElement("gift_name").setText(opd.getProdName());
							x_gift.addElement("gift_product_id").setText("");
							x_gift.addElement("gift_spec_id").setText("");
						}
					}

				}
			}
			x_order.addElement("totalprice").setText("" + order.getTotalPrice().floatValue());
			x_order.addElement("paytype").setText(
					StringUtils.defaultIfEmpty(paymentTpMenu.getOptions().get(order.getPaymentTp()).getName(), ""));
			x_order.addElement("orderstatus").setText(
					StringUtils.defaultIfEmpty(orderStMenu.getOptions().get(order.getOrderSt()).getName(), ""));
			x_order.addElement("logisticfee").setText("" + order.getShipfare().floatValue());
			x_order.addElement("usebonus").setText("" + order.getBonus().floatValue());
			x_order.addElement("usecoupon").setText("" + order.getCoupon().floatValue());
			x_order.addElement("usediscount").setText("" + order.getDiscount().floatValue());
			x_order.addElement("codfee").setText("" + order.getCodFee().floatValue());
			x_order.addElement("depositpay").setText("" + order.getMyWallet().floatValue());

			Element x_deliver = x_order.addElement("deliver");
			x_deliver.addElement("sendname").setText(order.getReceiverName());

			if (StringUtils.isNotBlank(order.getReceiverPhoneArea())
					&& !"0".equals(order.getReceiverPhoneArea().substring(0, 1))) {
				x_deliver.addElement("telarea").setText("0" + order.getReceiverPhoneArea());
			} else {
				x_deliver.addElement("telarea").setText(StringUtils.defaultString(order.getReceiverPhoneArea()));
			}
			x_deliver.addElement("tel").setText(StringUtils.defaultString(order.getReceiverPhone()));
			x_deliver.addElement("mobileno").setText(order.getReceiverMobile());
			x_deliver.addElement("province").setText(order.getReceiverProvince());
			x_deliver.addElement("city").setText(order.getReceiverCity());
			x_deliver.addElement("district").setText(order.getReceiverArea());
			x_deliver.addElement("address").setText(order.getReceiverAddr());
			x_deliver.addElement("zip").setText(order.getReceiverZip());

			if (StringUtils.equalsIgnoreCase(order.getInvoiceTp(), "01")) {
				x_order.addElement("invoicinfo").setText("发票抬头个人");
			} else {
				x_order.addElement("invoicinfo").setText(order.getInvoiceTitle());
			}

			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getorderdetail error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getorderdetail error :{}", e.toString());
			this.createErrorResult("获取失败", "weblogid有问题");
		}

		return "finish";
	}

	/**
	 * 27.修改订单讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String mdyorder() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String orderId = request.getParameter("orderno");
		String codtype = request.getParameter("codtype");

		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String district = request.getParameter("district");
		String address = request.getParameter("address");
		String zip = request.getParameter("zip");
		String receivername = request.getParameter("receivername");
		String mobile = request.getParameter("mobile");
		String telArea = request.getParameter("telarea");
		String tel = request.getParameter("telno");
		String ext = request.getParameter("ext");

		String invoiceType = request.getParameter("invoicetype");
		String invoice = request.getParameter("invoice");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			if (StringUtils.isBlank(orderId)) {
				throw new YekMobileException("传递参数不正确");
			}

			Orders order = orderService.get(orderId);

			if (order == null) {
				throw new YekMobileException("订单不存在");
			}

			if (StringUtils.isNotBlank(codtype)) { // 变更支付方式
				// 预设30
				String payTp = "30";
				if (StringUtils.equalsIgnoreCase(codtype, "pos")) {
					payTp = "60";
				}
				try {
					orderModifyService.updateOrderPaymentTp(orderId, payTp, false, memberId, ""); // 拆单用""
				} catch (CoreException e) {
					if (OrderModifyService.ERROR_ORDER_MODIFY_PAYTYPE_Y3060N00.equals(e.getMessage())) {
						throw new YekMobileException("订单审核中，不可修改");
					} else if (OrderModifyService.ERROR_ORDER_MUSTPAY_BIGGER_VIRTUALBALANCE.equals(e.getMessage())) {
						throw new YekMobileException("需付金额大于账户余额，不可修改");
					}
				}
			} else if (StringUtils.isNotBlank(invoiceType) && StringUtils.isNotBlank(invoice)) { // 修改发票讯息
				if (StringUtils.equals(invoiceType, "C")) { // 单位
					order.setInvoiceTp("02");
					order.setInvoiceTitle(invoice);
				} else if (StringUtils.equals(invoiceType, "P")) { // 个人
					order.setInvoiceTp("01");
					order.setInvoiceTitle("");
				}
				orderModifyService.update(order);
			} else { // 变更收货人信息
				if (StringUtils.isBlank(receivername)) {
					throw new YekMobileException("传递参数不正确");
				}
				if (StringUtils.isBlank(mobile)) {
					throw new YekMobileException("传递参数不正确");
				}

				boolean canSave = true;
				Map<String, Object> attrs = new HashMap<String, Object>();
				attrs.put("contactName", receivername);
				attrs.put("areaCode", telArea.trim());
				attrs.put("phone", tel.trim());
				attrs.put("extension", ext.trim());
				attrs.put("mobile", mobile);
				if (province == null) {
					province = order.getReceiverProvince();
				}
				if (city == null) {
					city = order.getReceiverCity();
				}
				if (address == null) {
					address = order.getReceiverAddr();
				}
				attrs.put("province", province);
				attrs.put("city", city);
				attrs.put("addr", address);
				if ("30".equals(order.getReceiverTp())) {// 達芙妮
					// if (district == null) {
					// district = order.getReceiverArea();
					// }
					// if (storeId == null) {
					// storeId = order.getStoreId();
					// }
					// attrs.put("district", district);
					// attrs.put("storeId", storeId);
				} else {
					if (zip == null) {
						zip = order.getReceiverZip();
					}
					if (zip.length() > 6 || !(Integer.parseInt(zip) > 0)) {
						canSave = false;
					}

					if (district == null) {
						district = order.getReceiverArea();
					}
					attrs.put("zipCode", zip);
					district = district.split(",")[0];
					if (district.substring(0, 1).equals("※")) {
						district = district.substring(1);
					}
					attrs.put("district", district);
					attrs.put("version", "");
				}
				if (canSave) {
					orderModifyService.updateOrderAddres(orderId, attrs);
				} else {
					throw new YekMobileException("zipCode error");
				}
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.mdyorder error :{}", e.toString());
			this.createErrorResult("提交失敗", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.mdyorder error :{}", e.toString());
			this.createErrorResult("提交失败", "提交结帐数据有误，电话号码格式有问题");
		}

		return "finish";
	}

	/**
	 * 28.删除订单讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String delorder() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String orderId = request.getParameter("orderno");
		String reason = request.getParameter("reason");
		String description = request.getParameter("appendnote");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			if (StringUtils.isBlank(orderId)) {
				throw new YekMobileException("传递参数不正确");
			}

			Orders order = orderService.get(orderId);

			if (order == null) {
				throw new YekMobileException("订单不存在");
			}

			if (!("00".equals(order.getOrderSt()) || "10".equals(order.getOrderSt()) || "20".equals(order.getOrderSt()))) {
				throw new YekMobileException("订单状态为订审核中，等待付款，等待配货的情形下才可以取消");
			}

			if (order.getMemberId().equals(memberId)) {
				String host = request.getHeader("X-Forwarded-For");
				if (StringUtils.isBlank(host)) {
					host = StringUtils.defaultString(request.getRemoteAddr(), "0.0.0.0");
				} else if (host.length() > 100) {
					host = host.substring(0, 100);
				}

				serviceOrderService.cancelOrderByUser(orderId, description, reason, memberId, host, "");
			} else {
				throw new YekMobileException("您无权操作本订单！");
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.delorder error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.delorder error :{}", e.toString());
			this.createErrorResult("获取失败", "weblogid有问题");
		}

		return "finish";
	}

	/**
	 * 29.获取可用购物金讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String gebonuslist() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String couponno = request.getParameter("orderno");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			CommonCriteria crit = new CommonCriteria();
			crit = new CommonCriteria();
			crit.addEq("memberId", memberId);
			crit.addGe("expireDate", DateUtils.addMonths(new Date(), -6));
			List<Bonus> bonusList = memberService.getBonusList(crit, new String[] { "createDate" });

			crit = new CommonCriteria();
			crit.addEq("memberId", memberId);
			crit.addGe("createDate", DateUtils.addMonths(new Date(), -6));
			List<BonusTransfer> bonustransferList = transferService.getBonusTransferList(0, -1, crit,
					new String[] { "createDate" });

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			for (Bonus bonus : bonusList) {
				Element x_getbonus = x_dataset.addElement("getbonus");
				if (StringUtils.isNotBlank(bonus.getOrderId())) {
					x_getbonus.addElement("orderno").setText(bonus.getOrderId());
				} else {
					x_getbonus.addElement("orderno").setText("--");
				}
				x_getbonus.addElement("getdate").setText(df.format(bonus.getCreateDate()));
				x_getbonus.addElement("getsource").setText(bonus.getDescription());
				x_getbonus.addElement("price").setText(bonus.getTrxAmount().toString());
				if (bonus.getTrxType().equals("ORDER_CANCEL") || bonus.getTrxType().equals("ORDER_RETURNED")) {
					x_getbonus.addElement("startdate").setText("已取消");
					x_getbonus.addElement("enddate").setText("");
				} else {
					x_getbonus.addElement("startdate").setText(df.format(bonus.getStartDate()));
					x_getbonus.addElement("enddate").setText(df.format(bonus.getExpireDate()));
				}
			}

			for (BonusTransfer bonusTransfer : bonustransferList) {
				if (bonusTransfer.getRefoundBonus().compareTo(new BigDecimal(0)) != 0) {
					Element x_usebonus = x_dataset.addElement("usebonus");
					x_usebonus.addElement("orderno").setText(StringUtils.defaultIfEmpty(bonusTransfer.getOrderId(), ""));
					x_usebonus.addElement("getdate").setText(df.format(bonusTransfer.getCreateDate()));

					StringBuilder sb = new StringBuilder();
					sb.append("商品退货/取消完成，归还积分。");
					if (StringUtils.isNotBlank(bonusTransfer.getOrderId())) {
						sb.append("(订单编号：").append(bonusTransfer.getOrderId()).append("");
					}
					x_usebonus.addElement("reference").setText(sb.toString());
					x_usebonus.addElement("price").setText("");
					x_usebonus.addElement("returnprice").setText(bonusTransfer.getRefoundBonus().toString());
				}

				if (bonusTransfer.getUseBonus().compareTo(new BigDecimal(0)) != 0) {
					Element x_usebonus = x_dataset.addElement("usebonus");
					x_usebonus.addElement("orderno").setText(StringUtils.defaultIfEmpty(bonusTransfer.getOrderId(), ""));
					x_usebonus.addElement("getdate").setText(df.format(bonusTransfer.getCreateDate()));

					StringBuilder sb = new StringBuilder();
					sb.append("折抵订单 ");
					if (StringUtils.isNotBlank(bonusTransfer.getOrderId())) {
						sb.append("订单编号：").append(bonusTransfer.getOrderId());
					}
					x_usebonus.addElement("reference").setText(sb.toString());
					x_usebonus.addElement("price").setText(bonusTransfer.getUseBonus().toString());
					x_usebonus.addElement("returnprice").setText("");

				}
			}

			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.gebonuslist error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.gebonuslist error :{}", e.toString());
			this.createErrorResult("获取失败", "weblogid有问题");
		}

		return "finish";
	}

	/**
	 * 30.获取可用礼卷讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getcouponlist() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String couponno = request.getParameter("orderno");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			// 捞出六个月内获得礼卷
			List<CouponItem> couponList = couponService.getListItems(memberId);
			for (CouponItem coupon : couponList) {
				Element x_coupon = x_dataset.addElement("coupon");
				x_coupon.addElement("getdate").setText(df.format(coupon.getRegDate()));
				StringBuilder sb = new StringBuilder();
				sb.append(coupon.getCoupon().getName()).append("-").append(coupon.getCoupon().getDescription());
				x_coupon.addElement("getsource").setText(sb.toString());
				x_coupon.addElement("use").setText("N");
				x_coupon.addElement("orderno").setText("");
				x_coupon.addElement("price").setText(coupon.getCoupon().getFaceValue().setScale(1).toString());
				x_coupon.addElement("startdate").setText(df.format(coupon.getStartDate()));
				x_coupon.addElement("enddate").setText(df.format(coupon.getEndDate()));

				Coupon.ApplyRangType applyRangeType = coupon.getCoupon().getApplyRangeType();

				List<String> applicableItemIdList = new ArrayList<String>();

				String[] applyRangeExtensionArray = coupon.getCoupon().getApplyRangeTypeExtensionArray();
				for (String applyRangeExtension : applyRangeExtensionArray) {
					switch (applyRangeType) {
					case CATEGORY:
						String categoryPath = applyRangeExtension;
						String[] categoryPathArray = StringUtils.split(categoryPath, '/');

						if (categoryPathArray == null) {
							break;
						}
						if (categoryPathArray.length <= 0) {
							break;
						}
						String categoryIdString = categoryPathArray[categoryPathArray.length - 1];
						if (!StringUtils.isNumeric(categoryIdString)) {
							break;
						}

						Long categoryId = Long.parseLong(categoryIdString);

						// 檢查分類是否存在
						Category category = categoryService.getCategoryById(categoryId);
						if (category == null) {
							break;
						}

						if (!categoryPath.equals(category.getCategoryPath())) {
							break;
						}

						applicableItemIdList.add(categoryIdString);
						break;
					case PRODUCT:
						String productId = applyRangeExtension;

						Product product = productService.get(productId);
						// 檢查商品是否存在
						if (product == null) {
							break;
						}

						Shelf shelf = shelfService.getShelfByProductId(productId, DateUtil.getCurrentTime(),
								DateUtil.getCurrentTime());
						// 檢查是否有上架檔
						if (shelf == null) {
							break;
						}

						// 檢查是否有價格
						if (shelf.getShelfPrice() == null) {
							break;
						}

						// 檢查商品價格是否大於等於最低商品價格
						if (shelf.getShelfPrice().doubleValue() < coupon.getCoupon().getMinimumProductPrice().doubleValue()) {
							break;
						}

						applicableItemIdList.add(productId);
						break;
					}
				}

				Element x_condition = x_coupon.addElement("condition");
				switch (coupon.getCoupon().getApplyRangeType()) {
				case ALL:
					x_condition.addElement("title").setText(
							"限折抵单件金额满" + coupon.getCoupon().getMinimumProductPrice().toString() + "元，全站适用");
					break;
				case CATEGORY:
					x_condition.addElement("title").setText(
							"限折抵单件金额满" + coupon.getCoupon().getMinimumProductPrice().toString() + "元，适用商品馆/类别如下：");
					for (String applicableItemId : applicableItemIdList) {
						Element x_category = x_condition.addElement("category");
						x_category.addElement("catid").setText(applicableItemId);
						x_category.addElement("catname").setText(
								categoryService.makeCategorieURL(NumberUtils.toLong(applicableItemId), false));
					}
					break;
				case PRODUCT:
					x_condition.addElement("title").setText(
							"限折抵单件金额满" + coupon.getCoupon().getMinimumProductPrice().toString() + "元，适用商品如下：");
					for (String applicableItemId : applicableItemIdList) {
						Element x_product = x_condition.addElement("product");
						x_product.addElement("productid").setText(applicableItemId);
						x_product.addElement("productname").setText(productService.get(applicableItemId).getProductName());
					}
					break;
				}
			}

			// 取得該 member 六個月內使用過的 coupon item
			couponList = couponService.getUsedItems(memberId);
			for (CouponItem coupon : couponList) {
				Element x_coupon = x_dataset.addElement("coupon");
				x_coupon.addElement("getdate").setText(df.format(coupon.getRegDate()));
				StringBuilder sb = new StringBuilder();
				sb.append(coupon.getCoupon().getName()).append("-").append(coupon.getCoupon().getDescription());
				x_coupon.addElement("getsource").setText(sb.toString());
				x_coupon.addElement("use").setText("Y");
				x_coupon.addElement("orderno").setText(coupon.getOrderId());
				x_coupon.addElement("price").setText(coupon.getCoupon().getFaceValue().setScale(1).toString());
				x_coupon.addElement("startdate").setText(df.format(coupon.getStartDate()));
				x_coupon.addElement("enddate").setText(df.format(coupon.getEndDate()));

				Coupon.ApplyRangType applyRangeType = coupon.getCoupon().getApplyRangeType();

				List<String> applicableItemIdList = new ArrayList<String>();

				String[] applyRangeExtensionArray = coupon.getCoupon().getApplyRangeTypeExtensionArray();
				for (String applyRangeExtension : applyRangeExtensionArray) {
					switch (applyRangeType) {
					case CATEGORY:
						String categoryPath = applyRangeExtension;
						String[] categoryPathArray = StringUtils.split(categoryPath, '/');

						if (categoryPathArray == null) {
							break;
						}
						if (categoryPathArray.length <= 0) {
							break;
						}
						String categoryIdString = categoryPathArray[categoryPathArray.length - 1];
						if (!StringUtils.isNumeric(categoryIdString)) {
							break;
						}

						Long categoryId = Long.parseLong(categoryIdString);

						// 檢查分類是否存在
						Category category = categoryService.getCategoryById(categoryId);
						if (category == null) {
							break;
						}

						if (!categoryPath.equals(category.getCategoryPath())) {
							break;
						}

						applicableItemIdList.add(categoryIdString);
						break;
					case PRODUCT:
						String productId = applyRangeExtension;

						Product product = productService.get(productId);
						// 檢查商品是否存在
						if (product == null) {
							break;
						}

						Shelf shelf = shelfService.getShelfByProductId(productId, DateUtil.getCurrentTime(),
								DateUtil.getCurrentTime());
						// 檢查是否有上架檔
						if (shelf == null) {
							break;
						}

						// 檢查是否有價格
						if (shelf.getShelfPrice() == null) {
							break;
						}

						// 檢查商品價格是否大於等於最低商品價格
						if (shelf.getShelfPrice().doubleValue() < coupon.getCoupon().getMinimumProductPrice().doubleValue()) {
							break;
						}

						applicableItemIdList.add(productId);
						break;
					}
				}

				Element x_condition = x_coupon.addElement("condition");
				switch (coupon.getCoupon().getApplyRangeType()) {
				case ALL:
					x_condition.addElement("title").setText(
							"限折抵单件金额满" + coupon.getCoupon().getMinimumProductPrice().toString() + "元，全站适用");
					break;
				case CATEGORY:
					x_condition.addElement("title").setText(
							"限折抵单件金额满" + coupon.getCoupon().getMinimumProductPrice().toString() + "元，适用商品馆/类别如下：");
					for (String applicableItemId : applicableItemIdList) {
						Element x_category = x_condition.addElement("category");
						x_category.addElement("catid").setText(applicableItemId);
						x_category.addElement("catname").setText(
								categoryService.makeCategorieURL(NumberUtils.toLong(applicableItemId), false));
					}
					break;
				case PRODUCT:
					x_condition.addElement("title").setText(
							"限折抵单件金额满" + coupon.getCoupon().getMinimumProductPrice().toString() + "元，适用商品如下：");
					for (String applicableItemId : applicableItemIdList) {
						Element x_product = x_condition.addElement("product");
						x_product.addElement("productid").setText(applicableItemId);
						x_product.addElement("productname").setText(productService.get(applicableItemId).getProductName());
					}
					break;
				}
			}

			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcouponlist error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcouponlist error :{}", e.toString());
			this.createErrorResult("获取失败", "weblogid有问题");
		}

		return "finish";
	}

	/**
	 * 31.提交礼卷讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String setcoupon() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String couponno = request.getParameter("couponno");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			if (StringUtils.isBlank(couponno)) {
				throw new YekMobileException("Coupon No为null或空白");
			}

			if (couponno.length() != 10) {
				throw new YekMobileException("Coupon No长度不为10");
			}

			CouponItem couponItem = couponService.getCouponItemByCode(couponno);
			if (couponItem == null) {
				throw new YekMobileException("Coupon No不存在");
			}

			if (couponItem.getMemberId() != null) {
				throw new YekMobileException("Coupon No已充值");
			}

			Coupon coupon = couponItem.getCoupon();
			Date now = new Date();
			if (couponItem.getEndDate().before(now)) {
				throw new YekMobileException("Coupon已过期");
			}

			if (Coupon.Status.INACTIVE.equals(coupon.getStatus())) {
				throw new YekMobileException("Coupon已过期");
			}

			Member member = memberService.getMemberByLoginId(userData.getLoginId());

			if (coupon.getIsOnce().booleanValue()) {
				List<CouponItem> couponItemsOfMember = this.couponService.getCouponItemListByCouponAndMember(coupon, member);
				if (couponItemsOfMember != null && couponItemsOfMember.size() > 0) {
					throw new YekMobileException("此Coupon不能同一会员多张");
				}
			}

			couponService.regCouponItem(couponItem, memberId);

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.setcoupon error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.setcoupon error :{}", e.toString());
			this.createErrorResult("失败", "礼卷已使用");
		}
		return "finish";
	}

	/**
	 * 32.获取收货地址接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getaddresslist() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String cartId = request.getParameter("shopcartid");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			List<AddressBook> abList = null;
			if (StringUtils.isBlank(cartId)) {
				abList = memberService.getAddressBookList(memberId);
			} else {
				Map<String, String> drMap = deliveryRuleService.findDeliveryType("cart", cartId + "_yekmobile");
				String deliveryType = drMap.get("deliveryType");
				if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
					abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, drMap.get("fromProvince"),
							drMap.get("fromCity"), drMap.get("fromDistrict"));
				} else {
					// 大材积
					Map<String, String> prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(cartId + "_yekmobile");
					if (prodVolumeMap.size() > 0) {
						abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "", true);
					} else {
						abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "");
					}
				}
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			for (int i = 0; i < abList.size(); i++) {
				AddressBook ab = abList.get(i);
				Element x_addressinfo = x_dataset.addElement("addressinfo");
				x_addressinfo.addElement("addressid").setText(ab.getId().toString());
				x_addressinfo.addElement("receiver").setText(ab.getContactName());
				x_addressinfo.addElement("province").setText(ab.getProvince());
				x_addressinfo.addElement("city").setText(ab.getCity());
				x_addressinfo.addElement("district").setText(ab.getDistrict());
				x_addressinfo.addElement("address").setText(ab.getAddr());
				x_addressinfo.addElement("zip").setText(ab.getZipCode());

				if (StringUtils.isBlank(ab.getAreaCode())) {
					x_addressinfo.addElement("telarea").setText("");
				} else {
					x_addressinfo.addElement("telarea").setText(ab.getAreaCode());
				}
				if (StringUtils.isBlank(ab.getPhone())) {
					x_addressinfo.addElement("tel").setText("");
				} else {
					x_addressinfo.addElement("tel").setText(ab.getPhone());
				}
				// --------------------- Edit by Andy Chiang
				if (StringUtils.isBlank(ab.getExtension())) {
					x_addressinfo.addElement("tel_ext").setText("");
				} else {
					x_addressinfo.addElement("tel_ext").setText(ab.getExtension());
				}
				// ---------------------
				if (StringUtils.isBlank(ab.getMobile())) {
					x_addressinfo.addElement("mobileno").setText("");
				} else {
					x_addressinfo.addElement("mobileno").setText(ab.getMobile());
				}
				if (i == 0)
					x_addressinfo.addElement("default").setText("Y");
				else
					x_addressinfo.addElement("default").setText("N");
			}

			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getaddresslist error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getaddresslist error :{}", e.toString());
			this.createErrorResult("失败", "数据获取失败");
		}
		return "finish";
	}

	/**
	 * 33.提交收货地址接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String setaddress() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String addressId = request.getParameter("addressid");
		String receiver = request.getParameter("receiver");
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String district = request.getParameter("district");
		String address = request.getParameter("address");
		String zip = request.getParameter("zip");
		String telarea = request.getParameter("telarea");
		String tel = request.getParameter("tel");
		String ext = request.getParameter("ext");
		String mobileno = request.getParameter("mobileno");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			AddressBook adBook;
			if (StringUtils.isNotBlank(addressId)) {
				adBook = memberService.getAddressBook(Long.parseLong(addressId));
			} else {
				CommonCriteria crit = new CommonCriteria();
				crit.addEq("memberId", memberId);
				List<AddressBook> abList = memberService.getAddressBookList(crit);
				if (abList.size() >= 20) {
					throw new YekMobileException("error-超过20笔资料");
				}
				adBook = new AddressBook();
				adBook.setMemberId(memberId);
			}
			adBook.setContactName(receiver);
			adBook.setProvince(province);
			adBook.setCity(city);
			adBook.setDistrict(district);
			if (StringUtils.isBlank(zip)) {
				throw new YekMobileException("邮编必须输入");
			}
			adBook.setZipCode(zip);
			adBook.setAddr(address);
			adBook.setMobile(StringUtils.isBlank(mobileno) ? null : mobileno);
			if (StringUtils.isBlank(mobileno)) {
				throw new YekMobileException("手机必须输入");
			}
			if (StringUtils.isBlank(tel)) {
				adBook.setAreaCode(null);
				adBook.setPhone(null);
				adBook.setExtension(null);
			} else {
				adBook.setAreaCode(telarea);
				adBook.setPhone(tel);
				adBook.setExtension(StringUtils.isBlank(ext) ? null : ext);
			}
			if (memberService.checkAddressBookExist(adBook)) {
				throw new YekMobileException("资料已存在");
			} else {
				if (StringUtils.isNotBlank(addressId)) {
					adBook = memberService.updateAddressBook(adBook);
				} else {
					adBook = memberService.saveAddressBook(adBook);
				}
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.setaddress error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("YekMobileAction.setaddress error :{}", e.toString());
			// this.createErrorResult("失败", "数据有误");
			this.createErrorResult("失败", "数据有误", e.toString());
		}
		return "finish";
	}

	/**
	 * 34.删除收货地址接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String deladdress() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String addressId = request.getParameter("addressid");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			if (StringUtils.isBlank(addressId)) {
				throw new YekMobileException("传递参数不正确");
			}

			if (!memberService.deleteAddressBook(Long.parseLong(addressId))) {
				throw new YekMobileException("删除失败");
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.deladdress error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.deladdress error :{}", e.toString());
			this.createErrorResult("失败", "此数据不存在");
		}
		return "finish";
	}

	/**
	 * 35.获取商品问与答讯息列表接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getqalist() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			StringBuilder hql = new StringBuilder();
			hql.append("select prd.product_id x1 ,prd.product_name x2,cq.description x3,caw.content x4,to_char(cq.createdate,'yyyy/mm/dd') x5, to_char(wo.finishtime,'yyyy/mm/dd') x6 ");
			hql.append("from crm_work_order wo, crm_cs_question cq ,crm_cs_answer caw,crm_question_ev cqev,ec_product_main prd ");
			hql.append("where cq.type_name='CommonQuestion' and wo.domainid=cq.id and cq.id=caw.question_id ");
			hql.append("and wo.domainid=cqev.question_id ");
			hql.append("and cqev.name='productId' ");
			hql.append("and cqev.value=prd.product_id ");
			hql.append("and cq.memberid ='").append(memberId).append("'");
			Object[] results = null;

			results = baseMgr.queryBySql(hql.toString(), new Object[] {});
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			for (int i = 0; i < results.length; i++) {
				Map valueMap = (Map) results[i];
				Element x_qa = x_dataset.addElement("qa");
				String prodId = valueMap.get("X1").toString();
				x_qa.addElement("prodictid").setText(prodId);
				x_qa.addElement("productname").setText(valueMap.get("X2").toString());
				String imgUrl = ServerValue.getImgDomain() + "/PImg/" + prodId.substring(0, 4) + "/" + prodId + "/" + prodId
						+ "_m100.jpg";
				x_qa.addElement("image_s_url").setText(imgUrl);
				x_qa.addElement("question").setText(valueMap.get("X3").toString());
				x_qa.addElement("answer").setText(StringUtils.defaultIfEmpty(valueMap.get("X4").toString(), ""));
				x_qa.addElement("qadate").setText(valueMap.get("X5").toString());
				if (valueMap.get("X6") != null) {
					x_qa.addElement("awdate").setText(valueMap.get("X6").toString());
				}
			}

			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getqalist error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getqalist error :{}", e.toString());
			this.createErrorResult("失败", "此数据不存在");
		}
		return "finish";
	}

	/**
	 * 36.提交商品问与答接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String setqa() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String productId = request.getParameter("prodictid");
		String question = request.getParameter("question");
		try {
			UserData userData = new UserData(request, response);
			String memberId = userData.getMemberId();
			if (memberId == null) {
				throw new YekMobileException("使用者尚未登入");
			}

			boolean isMember = true;
			String content = HtmlRegexUtil.secureMatch(question);
			String email = "";
			csService.createProductQuestion(isMember, email, memberId, productId, content);
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.setqa error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.setqa error :{}", e.toString());
			this.createErrorResult("失败", "提交数据有误");
		}
		return "finish";
	}

	/**
	 * 37.获取推荐讯息列表接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getrec() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String recId = request.getParameter("recid");
		try {
			if (StringUtils.isBlank(recId)) {
				throw new YekMobileException("传递参数不正确");
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");
			x_dataset.addElement("rectype").setText(recId);

			List<Menu> list = new ArrayList<Menu>();
			CommonCriteria crit = new CommonCriteria();
			crit.addRlike("key", recId);
			list = menuService.getList(0, -1, crit, new String[] { "key asc" });

			if (StringUtils.equalsIgnoreCase(recId, "mobile_main_rec")) { // 大看板
				for (Menu menu : list) {
					if (!"D".equals(menu.getType())) {
						Element x_rec = x_dataset.addElement("rec");
						x_rec.addElement("recid").setText(menu.getKey());
						x_rec.addElement("recimageurl").setText(menu.getMemo());
					}
				}
			} else if (StringUtils.equalsIgnoreCase(recId, "mobile_week_rec")) { // 本周推荐
				for (Menu menu : list) {
					if (!"D".equals(menu.getType())) {
						Element x_rec = x_dataset.addElement("rec");
						x_rec.addElement("recid").setText(menu.getKey());
						x_rec.addElement("rectitle").setText(menu.getDescription());
					}
				}
			} else if (StringUtils.equalsIgnoreCase(recId, "mobile_brand_rec")) { // 品牌蓷荐
				for (Menu menu : list) {
					if (!"D".equals(menu.getType())) {
						Element x_rec = x_dataset.addElement("rec");
						x_rec.addElement("recid").setText(menu.getKey());
						x_rec.addElement("recimageurl").setText(menu.getMemo());
						x_rec.addElement("rectitle").setText(menu.getDescription());
					}
				}
			}
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getrec error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getrec error :{}", e.toString());
			this.createErrorResult("失败", "提交数据有误");
		}
		return "finish";
	}

	/**
	 * 38.获取推荐详细讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getrecdetail() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String recId = request.getParameter("recid");
		try {
			if (StringUtils.isBlank(recId)) {
				throw new YekMobileException("传递参数不正确");
			}

			Menu menu = menuService.get(recId);
			if (menu == null) {
				throw new YekMobileException("recId(" + recId + ")不存在");
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			if (recId.indexOf("mobile_main_rec") > -1) { // 大看板
				x_dataset.addElement("rectype").setText("mobile_main_rec");

				Map<String, Option> options = menu.getOptions();
				Iterator<String> keyIter = options.keySet().iterator();
				while (keyIter.hasNext()) {
					String key = keyIter.next();
					Option option = options.get(key);
					String productId = option.getName();
					Product product = productService.get(productId);
					Shelf shelf = shelfService.getShelfByProductId(productId, DateUtil.getCurrentTime(),
							DateUtil.getCurrentTime());
					if (null != product && null != shelf)
						if ("0".equals(product.getProductTypeStr()) || "4".equals(product.getProductTypeStr())) // Edit by Andy江
																																																		// 滤掉其他特殊商品
						{
							Element x_rec = x_dataset.addElement("rec");
							x_rec.addElement("reckey").setText(key);

							x_rec.addElement("product_id").setText(productId);
							String imgUrl = ServerValue.getImgDomain() + "/PImg/" + productId.substring(0, 4) + "/" + productId + "/"
									+ productId + "_m75.jpg";
							x_rec.addElement("productimaeurl").setText(imgUrl);
							x_rec.addElement("product_name").setText(product.getProductName());
							x_rec.addElement("product_price").setText("" + shelf.getShelfPrice().floatValue());
						}
				}
			} else if (recId.indexOf("mobile_week_rec") > -1) { // 本周推荐
				x_dataset.addElement("rectype").setText("mobile_week_rec");

				Map<String, Option> options = menu.getOptions();
				Iterator<String> keyIter = options.keySet().iterator();
				Product product = new Product();
				Shelf shelfx = new Shelf();
				while (keyIter.hasNext()) {
					String key = keyIter.next();
					Option option = options.get(key);
					String productId = option.getName();
					product = productService.get(productId);
					shelfx = shelfService.getShelfByProductId(productId, DateUtil.getCurrentTime(), DateUtil.getCurrentTime());
					if (null != product && null != shelfx)
						if ("0".equals(product.getProductTypeStr()) || "4".equals(product.getProductTypeStr())) // Edit by Andy江
																																																		// 滤掉其他特殊商品
						{
							Element x_rec = x_dataset.addElement("rec");
							x_rec.addElement("reckey").setText(key);
							x_rec.addElement("product_id").setText(productId);
							String imgUrl = ServerValue.getImgDomain() + "/PImg/" + productId.substring(0, 4) + "/" + productId + "/"
									+ productId + "_m75.jpg";
							x_rec.addElement("productimaeurl").setText(imgUrl);
							x_rec.addElement("product_name").setText(product.getProductName());
							x_rec.addElement("product_price").setText("" + shelfx.getShelfPrice().floatValue());
						}
				}
			} else if (recId.indexOf("mobile_brand_rec") > -1) { // 品牌蓷荐
				x_dataset.addElement("rectype").setText("mobile_brand_rec");

				Map<String, Option> options = menu.getOptions();
				Iterator<String> keyIter = options.keySet().iterator();
				while (keyIter.hasNext()) {
					String key = keyIter.next();
					Option option = options.get(key);

					Element x_rec = x_dataset.addElement("rec");
					x_rec.addElement("reckey").setText(key);
					x_rec.addElement("keyword").setText(option.getName());
				}
			}

			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getrecdetail error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getrecdetail error :{}", e.toString());
			this.createErrorResult("失败", "提交数据有误");
		}
		return "finish";
	}

	/**
	 * 39.获取分类推荐讯息列表接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getcatrec() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String reccatId = request.getParameter("reccatid");
		try {
			List<Category> categories = new ArrayList<Category>();
			if (StringUtils.isBlank(reccatId)) {
				categories = categoryService.getChild(new Long(0));
			} else {
				categories = categoryService.getAvailableChild(NumberUtils.toLong(reccatId));
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			for (Category category : categories) {
				Element x_rec = x_dataset.addElement("rec");
				x_rec.addElement("reccatid").setText(category.getId().toString());

				x_rec.addElement("reccatname").setText(category.getName());
			}

			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcatrec error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcatrec error :{}", e.toString());
			this.createErrorResult("失败", "提交数据有误");
		}
		return "finish";
	}

	/**
	 * 40.获取分类推荐详细讯息接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getcatrecdetail() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		String reccatId = request.getParameter("reccatid");
		try {
			if (StringUtils.isBlank(reccatId)) {
				throw new YekMobileException("传递参数不正确");
			}

			// 判断是否level=1，如level=0，抓该节点下的第一个
			Category category = categoryService.get(Long.parseLong(reccatId));
			if (!StringUtils.equalsIgnoreCase(category.getLevel(), "1")) {
				if (StringUtils.equalsIgnoreCase(category.getLevel(), "0")) {
					List<Category> categories = categoryService.getAvailableChild(category.getId());
					if (categories.size() > 0) {
						reccatId = categories.get(0).getId().toString();
					} else {
						reccatId = "";
					}
				} else {
					throw new YekMobileException("传递参数不正确");
				}
			}

			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			if (!StringUtils.isBlank(reccatId)) { // 父类目下无子类目时，直接输出空的
				int shortRetroDays = viewReportProductClickService.rankShortDays();
				int longRetroDays = viewReportProductClickService.rankLongDays();
				int minimumRecordCount = viewReportProductClickService.mininumRecordSize();

				List<ViewReportProductClick> viewReportProductClickList = viewReportProductClickService.getTopRank(reccatId,
						shortRetroDays);
				if (viewReportProductClickList.size() < minimumRecordCount) {
					viewReportProductClickList = viewReportProductClickService.getTopRank(reccatId, longRetroDays);
				}

				Shelf shelfx = new Shelf();
				for (ViewReportProductClick click : viewReportProductClickList) {
					String productId = click.getPrimaryKey().getProductId();
					Product product = productService.get(productId); // Edit by Andy江
					shelfx = shelfService.getShelfByProductId(productId, DateUtil.getCurrentTime(), DateUtil.getCurrentTime()); // Edit
																																																											// by
																																																											// Andy江
					if (null != product.getProductTypeStr())
						if ("0".equals(product.getProductTypeStr()) || "4".equals(product.getProductTypeStr())) // Edit by Andy江
																																																		// 滤掉其他特殊商品
						{
							Element x_rec = x_dataset.addElement("rec");
							// x_rec.addElement("reckey").setText("");
							x_rec.addElement("product_id").setText(productId);
							String imgUrl = ServerValue.getImgDomain() + "/PImg/" + productId.substring(0, 4) + "/" + productId + "/"
									+ productId + "_m75.jpg";
							x_rec.addElement("productimaeurl").setText(imgUrl);
							x_rec.addElement("product_name").setText(click.getProductName());
							x_rec.addElement("product_price").setText(shelfx.getShelfPrice().toString()); // product.getPrpsShelfPrice().toString()
						}
				}
			}
			this.createSuccessResult(document);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcatrecdetail error :{}", e.toString());
			this.createErrorResult("失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.getcatrecdetail error :{}", e.toString());
			this.createErrorResult("失败", "提交数据有误");
		}
		return "finish";
	}

	/**
	 * 41. 增加提交到结算中心接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String dealcart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		List<CartOrderProduct> cartOrderProductList = null;

		BigDecimal c_total = BigDecimal.valueOf(0.0);
		BigDecimal c_discount = BigDecimal.valueOf(0.0);
		BigDecimal codFee = BigDecimal.valueOf(0.0);
		BigDecimal www = BigDecimal.valueOf(0.0);
		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			CartOrders cartOrders = cartOrdersService.getCart(memberId, memberId + "_yekmobile");
			if (memberId.equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			}
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			if (cartOrders != null) {
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				// optional.put("domain", "www.yaodian100.com");
				// optional.put("cookie", "yaodian100");
				cartOrders = cartOrdersService.calculateCart(cartOrders, optional); // 每次從新計算shopping cart的金額

				cartOrderProductList = cartOrders.getCartOrderProducts();
				CommonCriteria crit = new CommonCriteria();

				x_dataset.addElement("shopcartid").setText(cartOrders.getCartId().split("_")[0]); // 购物车ID
				List<CartOrderProduct> overbuyList = new ArrayList<CartOrderProduct>();
				for (CartOrderProduct cartOrderProduct : cartOrderProductList) {
					if (cartOrderProduct.getProdTp().equals("5")) {
						overbuyList.add(cartOrderProduct);
						continue;
					}
					List<String> tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());

					Element x_shoppingcart = x_dataset.addElement("shoppingcart");
					x_shoppingcart.addElement("cart_id").setText(formatToString(cartOrders.getCartId().split("_")[0]));
					x_shoppingcart.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_shoppingcart.addElement("cart_order_product_id").setText(
							formatToString(cartOrderProduct.getCartOrderProdId()));
					x_shoppingcart.addElement("campaign_id").setText(formatToString(cartOrderProduct.getCampaignId()));
					x_shoppingcart.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					x_shoppingcart.addElement("campaign_name").setText(formatToString(cartOrderProduct.getCampaignName()));
					x_shoppingcart.addElement("category_Path").setText(formatToString(cartOrderProduct.getCategoryPath()));
					int c = 0;
					if (tlpList != null) {
						for (int b = 0; b < tlpList.size(); b++) {
							if (tlpList.get(b).equals(cartOrderProduct.getProdId())) {
								x_shoppingcart.addElement("promote_name").setText("timelimitsales");
								c = 1;
							}
						}
					}
					if (c == 0) {
						x_shoppingcart.addElement("promote_name").setText("");
					}
					x_shoppingcart.addElement("product_spec_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_shoppingcart.addElement("product_spec_name").setText(formatToString(cartOrderProduct.getProdSpecName()));
					x_shoppingcart.addElement("product_Tp").setText(formatToString(cartOrderProduct.getProdTp()));

					x_shoppingcart.addElement("discount").setText(String.valueOf(cartOrderProduct.getDiscount()));
					x_shoppingcart.addElement("qty").addText(String.valueOf(cartOrderProduct.getQty()));
					x_shoppingcart.addElement("unit_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_shoppingcart.addElement("total_price").setText(formatToString(cartOrderProduct.getTotalPrice()));
					Product product = product2Service.get(cartOrderProduct.getProdId());
					if ((product.getProductType() != 6 && "N".equals(product.getCanUseCod())) || "Y".equals(product.getIsScm())) {
						x_shoppingcart.addElement("canusecod").setText("N");
					} else {
						x_shoppingcart.addElement("canusecod").setText("Y");
					}
					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總購物車商品金額
					c_discount = c_discount.add(cartOrderProduct.getDiscount());

					crit.addEq("productId", formatToString(cartOrderProduct.getProdId()));
					crit.addEq("type", "MAIN");
					crit.addEq("isDelete", "N");
					List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
					int b1 = 0;
					for (Image img : images) {
						if (img.getImgFilePath().indexOf("_m135") != -1) {
							x_shoppingcart.addElement("image_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
							b1 = 1;
							break;
						}
					}
					if (b1 == 0) {
						x_shoppingcart.addElement("image_path").addText("");
					}

					List<CartOrderProductDetail> details = cartOrderProduct.getDetails();
					for (CartOrderProductDetail prodDetail : details) {
						if (prodDetail.getDetailTp().equals("2")) {
							Element x_gift = x_shoppingcart.addElement("gift");
							x_gift.addElement("gift_product_id").setText(prodDetail.getProdId());
							x_gift.addElement("gift_product_name").setText(prodDetail.getProdName());
						}
					}

					if ("6".equals(cartOrderProduct.getProdTp())) { // n-m
						for (CartOrderProductDetail prodDetail : details) {
							Element x_npickm = x_shoppingcart.addElement("npickm");
							x_npickm.addElement("npickm_product_id").setText(prodDetail.getProdId());
							x_npickm.addElement("npickm_product_name").setText(prodDetail.getProdName());
							x_npickm.addElement("npickm_specification_id").setText(prodDetail.getProdSpecId());
							x_npickm.addElement("npickm_specification_name").setText(prodDetail.getProdSpecName());
							x_npickm.addElement("npickm_product_image").setText(
									ServerValue.getImgDomain() + "/PImg/" + prodDetail.getProdId().substring(0, 4) + "/"
											+ prodDetail.getProdId() + "/" + prodDetail.getProdId() + "_m75.jpg");
						}
					}
				}

				for (CartOrderProduct cartOrderProduct : overbuyList) {
					Element x_overbuy = x_dataset.addElement("overbuy");
					x_overbuy.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_overbuy.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					Shelf shelf = shelfService.getShelfByProductId(cartOrderProduct.getProdId(), DateUtil.getCurrentTime(),
							DateUtil.getCurrentTime());
					x_overbuy.addElement("shelf_price").setText(formatToString(shelf.getShelfPrice()));
					x_overbuy.addElement("overbuy_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_overbuy.addElement("specification_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_overbuy.addElement("specification_name").setText(formatToString(cartOrderProduct.getProdSpecName()));

					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總加購商品金額

				}

				// ------------ 產生符合COD模式的Address
				String cartId = request.getParameter("cartid");
				// UserData userData = new UserData(request, response);
				// String memberId = userData.getMemberId();
				if (memberId == null) {
					throw new YekMobileException("使用者尚未登入");
				}

				if (StringUtils.isBlank(cartId)) {
					throw new YekMobileException("未输入cartId");
				}
				cartId = cartId + "_yekmobile";
				if (false == deliveryRuleService.chkProdDetailCanUseCod("cart", cartId)) {
					throw new YekMobileException("此购物车商品不能使用货到付款");
				}

				List<AddressBook> abList = null;
				if (StringUtils.isBlank(cartId)) {
					// abList = memberService.getAddressBookList(memberId);
				} else {
					Map<String, String> drMap = deliveryRuleService.findDeliveryType("cart", cartId);
					String deliveryType = drMap.get("deliveryType");
					if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
						abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType,
								drMap.get("fromProvince"), drMap.get("fromCity"), drMap.get("fromDistrict"));
					} else {
						// 大材积
						Map<String, String> prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(cartId + "_yekmobile");
						if (prodVolumeMap.size() > 0) {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "", true);
						} else {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "");
						}
					}
				}
				// for (int i = 0; i < abList.size(); i++) {
				// AddressBook ab = abList.get(i);
				AddressBook ab = null;
				if (abList.size() > 0) {
					ab = abList.get(0);
					// COD﹣收取手續費
					codFee = addressService.getCodFee();
					// 運費
					www = addressService.getFreight(ab.getProvince(), cartOrders.getWeightSum().multiply(new BigDecimal("1000")),
							cartOrders.getAmount().add(cartOrders.getDiscount()), cartOrders.getDiscount());
					Element x_addressinfo = x_dataset.addElement("addressinfo");
					x_addressinfo.addElement("addressid").setText(ab.getId().toString());
					x_addressinfo.addElement("receiver").setText(ab.getContactName());
					x_addressinfo.addElement("province").setText(ab.getProvince());
					x_addressinfo.addElement("city").setText(ab.getCity());
					x_addressinfo.addElement("district").setText(ab.getDistrict());
					x_addressinfo.addElement("address").setText(ab.getAddr());
					x_addressinfo.addElement("zip").setText(ab.getZipCode());
					if (StringUtils.isBlank(ab.getAreaCode())) {
						x_addressinfo.addElement("telarea").setText("");
					} else {
						x_addressinfo.addElement("telarea").setText(ab.getAreaCode());
					}
					if (StringUtils.isBlank(ab.getPhone())) {
						x_addressinfo.addElement("tel").setText("");
					} else {
						x_addressinfo.addElement("tel").setText(ab.getPhone());
					}
					if (StringUtils.isBlank(ab.getMobile())) {
						x_addressinfo.addElement("mobileno").setText("");
					} else {
						x_addressinfo.addElement("mobileno").setText(ab.getMobile());
					}
					// if (i == 0)
					x_addressinfo.addElement("default").setText("Y");
					// else
					// x_addressinfo.addElement("default").setText("N");
					// }
				} else {
					document = DocumentHelper.createDocument();
					x_dataset = document.addElement("dataset");
					this.createSuccessResult(document, "无地址项目");
					return "finish";
				}
				// --------------------------------------
				String paytype = "cash";
				DeliveryRule dr = null;
				if (paytype.equals("pos")) {
					dr = deliveryRuleService.getCartDeliveryRule(cartId, ab.getProvince(), ab.getCity(), ab.getDistrict(), "30");
				} else {
					dr = deliveryRuleService.getCartDeliveryRule(cartId, ab.getProvince(), ab.getCity(), ab.getDistrict(), "20");
				}
				if (null == dr) {
					throw new YekMobileException("此地址不符合货到付款地址");
				}
				// ----------------产生加总XML讯息
				Element x_paytype = x_dataset.addElement("paytype");
				if (paytype.equals("pos")) {
					x_paytype.addElement("itemtype2").setText("货到付款-POS机");
				} else {
					x_paytype.addElement("itemtype1").setText("货到付款-现金");
				}
				Element x_summary = x_dataset.addElement("summary");
				x_summary.addElement("subtotal").setText(formatToString(c_total)); // 商品小计
				x_summary.addElement("carriage").setText(formatToString(www)); // 运费
				x_summary.addElement("poundage").setText(formatToString(codFee)); // 货到付款
				x_summary.addElement("cheapdiscount").setText(formatToString(c_discount)); // 折扣礼卷
				x_summary.addElement("cheapcoupon").setText("0.0"); // 折扣购物金
				x_summary.addElement("accountpay").setText("0.0"); // 账户余额支付
				x_summary.addElement("totalsum").setText(formatToString(c_total.subtract(c_discount).add(www).add(codFee))); // 你总共需要支付
				// --------------------------------------
			}

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误");
		}

		return "finish";
	}

	/**
	 * 42.增加修改结算中心接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkcart() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		List<CartOrderProduct> cartOrderProductList = null;

		BigDecimal c_total = BigDecimal.valueOf(0.0);
		BigDecimal c_discount = BigDecimal.valueOf(0.0);

		BigDecimal codFee = BigDecimal.valueOf(0.0);
		BigDecimal www = BigDecimal.valueOf(0.0);
		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			CartOrders cartOrders = cartOrdersService.getCart(memberId, memberId + "_yekmobile");
			if (memberId.equals(cartOrders.getCartId())) {
				cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			}
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			if (cartOrders != null) {
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				cartOrders = cartOrdersService.calculateCart(cartOrders, optional); // 每次從新計算shopping cart的金額

				cartOrderProductList = cartOrders.getCartOrderProducts();
				CommonCriteria crit = new CommonCriteria();

				x_dataset.addElement("shopcartid").setText(cartOrders.getCartId().split("_")[0]); // 购物车ID
				List<CartOrderProduct> overbuyList = new ArrayList<CartOrderProduct>();
				for (CartOrderProduct cartOrderProduct : cartOrderProductList) {
					if (cartOrderProduct.getProdTp().equals("5")) {
						overbuyList.add(cartOrderProduct);
						continue;
					}
					List<String> tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());

					Element x_shoppingcart = x_dataset.addElement("shoppingcart");
					x_shoppingcart.addElement("cart_id").setText(formatToString(cartOrders.getCartId().split("_")[0]));
					x_shoppingcart.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_shoppingcart.addElement("cart_order_product_id").setText(
							formatToString(cartOrderProduct.getCartOrderProdId()));
					x_shoppingcart.addElement("campaign_id").setText(formatToString(cartOrderProduct.getCampaignId()));
					x_shoppingcart.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					x_shoppingcart.addElement("campaign_name").setText(formatToString(cartOrderProduct.getCampaignName()));
					x_shoppingcart.addElement("category_Path").setText(formatToString(cartOrderProduct.getCategoryPath()));
					int c = 0;
					if (tlpList != null) {
						for (int b = 0; b < tlpList.size(); b++) {
							if (tlpList.get(b).equals(cartOrderProduct.getProdId())) {
								x_shoppingcart.addElement("promote_name").setText("timelimitsales");
								c = 1;
							}
						}
					}
					if (c == 0) {
						x_shoppingcart.addElement("promote_name").setText("");
					}
					x_shoppingcart.addElement("product_spec_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_shoppingcart.addElement("product_spec_name").setText(formatToString(cartOrderProduct.getProdSpecName()));
					x_shoppingcart.addElement("product_Tp").setText(formatToString(cartOrderProduct.getProdTp()));

					x_shoppingcart.addElement("discount").setText(String.valueOf(cartOrderProduct.getDiscount()));
					x_shoppingcart.addElement("qty").addText(String.valueOf(cartOrderProduct.getQty()));
					x_shoppingcart.addElement("unit_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_shoppingcart.addElement("total_price").setText(formatToString(cartOrderProduct.getTotalPrice()));
					Product product = product2Service.get(cartOrderProduct.getProdId());
					if ((product.getProductType() != 6 && "N".equals(product.getCanUseCod())) || "Y".equals(product.getIsScm())) {
						x_shoppingcart.addElement("canusecod").setText("N");
					} else {
						x_shoppingcart.addElement("canusecod").setText("Y");
					}
					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總購物車商品金額
					c_discount = c_discount.add(cartOrderProduct.getDiscount());

					crit.addEq("productId", formatToString(cartOrderProduct.getProdId()));
					crit.addEq("type", "MAIN");
					crit.addEq("isDelete", "N");
					List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
					int b1 = 0;
					for (Image img : images) {
						if (img.getImgFilePath().indexOf("_m135") != -1) {
							x_shoppingcart.addElement("image_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
							b1 = 1;
							break;
						}
					}
					if (b1 == 0) {
						x_shoppingcart.addElement("image_path").addText("");
					}

					List<CartOrderProductDetail> details = cartOrderProduct.getDetails();
					for (CartOrderProductDetail prodDetail : details) {
						if (prodDetail.getDetailTp().equals("2")) {
							Element x_gift = x_shoppingcart.addElement("gift");
							x_gift.addElement("gift_product_id").setText(prodDetail.getProdId());
							x_gift.addElement("gift_product_name").setText(prodDetail.getProdName());
						}
					}

					if ("6".equals(cartOrderProduct.getProdTp())) { // n-m
						for (CartOrderProductDetail prodDetail : details) {
							Element x_npickm = x_shoppingcart.addElement("npickm");
							x_npickm.addElement("npickm_product_id").setText(prodDetail.getProdId());
							x_npickm.addElement("npickm_product_name").setText(prodDetail.getProdName());
							x_npickm.addElement("npickm_specification_id").setText(prodDetail.getProdSpecId());
							x_npickm.addElement("npickm_specification_name").setText(prodDetail.getProdSpecName());
							x_npickm.addElement("npickm_product_image").setText(
									ServerValue.getImgDomain() + "/PImg/" + prodDetail.getProdId().substring(0, 4) + "/"
											+ prodDetail.getProdId() + "/" + prodDetail.getProdId() + "_m75.jpg");
						}
					}
				}

				for (CartOrderProduct cartOrderProduct : overbuyList) {
					Element x_overbuy = x_dataset.addElement("overbuy");
					x_overbuy.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_overbuy.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					Shelf shelf = shelfService.getShelfByProductId(cartOrderProduct.getProdId(), DateUtil.getCurrentTime(),
							DateUtil.getCurrentTime());
					x_overbuy.addElement("shelf_price").setText(formatToString(shelf.getShelfPrice()));
					x_overbuy.addElement("overbuy_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_overbuy.addElement("specification_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_overbuy.addElement("specification_name").setText(formatToString(cartOrderProduct.getProdSpecName()));

					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總加購商品金額

				}

				// ------------ 產生符合COD模式的Address
				String cartId = StringUtils.defaultString(request.getParameter("cartid"));
				if (StringUtils.isBlank(cartId)) {
					throw new YekMobileException("cartId未输入");
				}
				cartId = cartId + "_yekmobile";
				// UserData userData = new UserData(request, response);
				// String memberId = userData.getMemberId();
				if (memberId == null) {
					throw new YekMobileException("使用者尚未登入");
				}
				if (false == deliveryRuleService.chkProdDetailCanUseCod("cart", cartId)) {
					throw new YekMobileException("此购物车商品不能使用货到付款");
				}
				List<AddressBook> abList = null;
				if (StringUtils.isBlank(cartId)) {
					// abList = memberService.getAddressBookList(memberId);
				} else {
					Map<String, String> drMap = deliveryRuleService.findDeliveryType("cart", cartId);
					String deliveryType = drMap.get("deliveryType");
					if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
						abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType,
								drMap.get("fromProvince"), drMap.get("fromCity"), drMap.get("fromDistrict"));
					} else {
						// 大材积
						Map<String, String> prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(cartId);
						if (prodVolumeMap.size() > 0) {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "", true);
						} else {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "");

						}
					}
				}

				String addressed = StringUtils.defaultString(request.getParameter("addressed"));
				if (StringUtils.isBlank(addressed)) {
					throw new YekMobileException("addressed未输入");
				}
				AddressBook inputAddressBook = null;// 输入的地址簿
				AddressBook ab = null;// 最终可用的地址簿
				if (StringUtils.isNotBlank(addressed)) {
					inputAddressBook = memberService.getAddressBook(Long.parseLong(addressed));
				}
				if (null == inputAddressBook) {
					document = DocumentHelper.createDocument();
					x_dataset = document.addElement("dataset");
					this.createSuccessResult(document, "无地址项目");
					return "finish";
				}
				String paytype = StringUtils.defaultString(request.getParameter("paytype"));
				DeliveryRule dr = null;
				if (paytype.equals("cash")) {
					dr = deliveryRuleService.getCartDeliveryRule(cartId, inputAddressBook.getProvince(),
							inputAddressBook.getCity(), inputAddressBook.getDistrict(), "20");
				}
				if (paytype.equals("pos")) {
					dr = deliveryRuleService.getCartDeliveryRule(cartId, inputAddressBook.getProvince(),
							inputAddressBook.getCity(), inputAddressBook.getDistrict(), "30");
				}
				if (null == dr) {
					throw new YekMobileException("此地址不符合货到付款地址");
				}
				ab = inputAddressBook;
				if (null != ab) {

					// COD﹣收取手續費
					codFee = addressService.getCodFee();
					// 運費
					www = addressService.getFreight(ab.getProvince(), cartOrders.getWeightSum().multiply(new BigDecimal("1000")),
							cartOrders.getAmount().add(cartOrders.getDiscount()), cartOrders.getDiscount());
					Element x_addressinfo = x_dataset.addElement("addressinfo");
					x_addressinfo.addElement("addressid").setText(ab.getId().toString());
					x_addressinfo.addElement("receiver").setText(ab.getContactName());
					x_addressinfo.addElement("province").setText(ab.getProvince());
					x_addressinfo.addElement("city").setText(ab.getCity());
					x_addressinfo.addElement("district").setText(ab.getDistrict());
					x_addressinfo.addElement("address").setText(ab.getAddr());
					x_addressinfo.addElement("zip").setText(ab.getZipCode());
					if (StringUtils.isBlank(ab.getAreaCode())) {
						x_addressinfo.addElement("telarea").setText("");
					} else {
						x_addressinfo.addElement("telarea").setText(ab.getAreaCode());
					}
					if (StringUtils.isBlank(ab.getPhone())) {
						x_addressinfo.addElement("tel").setText("");
					} else {
						x_addressinfo.addElement("tel").setText(ab.getPhone());
					}
					if (StringUtils.isBlank(ab.getMobile())) {
						x_addressinfo.addElement("mobileno").setText("");
					} else {
						x_addressinfo.addElement("mobileno").setText(ab.getMobile());
					}
					// if (i == 0)
					// x_addressinfo.addElement("default").setText("Y");
					// else
					// x_addressinfo.addElement("default").setText("N");
				}

				// ----------------产生加总XML讯息
				Element x_paytype = x_dataset.addElement("paytype");

				if (paytype.equals("cash")) {
					x_paytype.addElement("itemtype").setText("货到付款-现金");
				}
				if (paytype.equals("pos")) {
					x_paytype.addElement("itemtype").setText("货到付款-POS机");
				}
				Element x_summary = x_dataset.addElement("summary");
				x_summary.addElement("subtotal").setText(formatToString(c_total)); // 商品小计
				x_summary.addElement("carriage").setText(formatToString(www)); // 运费
				x_summary.addElement("poundage").setText(formatToString(codFee)); // 货到付款
				x_summary.addElement("cheapdiscount").setText(formatToString(c_discount)); // 折扣礼卷
				x_summary.addElement("cheapcoupon").setText("0.0"); // 折扣购物金
				x_summary.addElement("accountpay").setText("0.0"); // 账户余额支付
				x_summary.addElement("totalsum").setText(formatToString(c_total.subtract(c_discount).add(www).add(codFee))); // 你总共需要支付
				// --------------------------------------
			}

			this.createSuccessResult(document);

		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误");
		}

		return "finish";
	}

	/**
	 * 43. 增加提交立即購買到结算中心接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String dealdirect() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		List<CartOrderProduct> cartOrderProductList = null;
		BigDecimal c_total = BigDecimal.valueOf(0.0);
		BigDecimal c_discount = BigDecimal.valueOf(0.0);
		BigDecimal codFee = BigDecimal.valueOf(0.0);
		BigDecimal www = BigDecimal.valueOf(0.0);
		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			// CartOrders cartOrders = cartOrdersService.getCart(memberId, memberId + "_yekmobile");
			CartOrders cartOrders = createBuyNowCart(request, userData);
			// if (memberId.equals(cartOrders.getCartId())) {
			// cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			// }
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			if (cartOrders != null) {
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				// optional.put("domain", "www.yaodian100.com");
				// optional.put("cookie", "yaodian100");
				cartOrders = cartOrdersService.calculateCart(cartOrders, optional); // 每次從新計算shopping cart的金額

				cartOrderProductList = cartOrders.getCartOrderProducts();
				CommonCriteria crit = new CommonCriteria();

				List<CartOrderProduct> overbuyList = new ArrayList<CartOrderProduct>();
				for (CartOrderProduct cartOrderProduct : cartOrderProductList) {
					if (cartOrderProduct.getProdTp().equals("5")) {
						overbuyList.add(cartOrderProduct);
						continue;
					}
					List<String> tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());

					Element x_shoppingcart = x_dataset.addElement("shoppingdirect");
					x_shoppingcart.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_shoppingcart.addElement("cart_order_product_id").setText(
							formatToString(cartOrderProduct.getCartOrderProdId()));
					x_shoppingcart.addElement("campaign_id").setText(formatToString(cartOrderProduct.getCampaignId()));
					x_shoppingcart.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					x_shoppingcart.addElement("campaign_name").setText(formatToString(cartOrderProduct.getCampaignName()));
					x_shoppingcart.addElement("category_Path").setText(formatToString(cartOrderProduct.getCategoryPath()));
					int c = 0;
					if (tlpList != null) {
						for (int b = 0; b < tlpList.size(); b++) {
							if (tlpList.get(b).equals(cartOrderProduct.getProdId())) {
								x_shoppingcart.addElement("promote_name").setText("timelimitsales");
								c = 1;
							}
						}
					}
					if (c == 0) {
						x_shoppingcart.addElement("promote_name").setText("");
					}
					x_shoppingcart.addElement("product_spec_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_shoppingcart.addElement("product_spec_name").setText(formatToString(cartOrderProduct.getProdSpecName()));
					x_shoppingcart.addElement("product_Tp").setText(formatToString(cartOrderProduct.getProdTp()));

					x_shoppingcart.addElement("discount").setText(String.valueOf(cartOrderProduct.getDiscount()));
					x_shoppingcart.addElement("qty").addText(String.valueOf(cartOrderProduct.getQty()));
					x_shoppingcart.addElement("unit_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_shoppingcart.addElement("total_price").setText(formatToString(cartOrderProduct.getTotalPrice()));
					Product product = product2Service.get(cartOrderProduct.getProdId());
					if ((product.getProductType() != 6 && "N".equals(product.getCanUseCod())) || "Y".equals(product.getIsScm())) {
						x_shoppingcart.addElement("canusecod").setText("N");
					} else {
						x_shoppingcart.addElement("canusecod").setText("Y");
					}
					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總購物車商品金額
					c_discount = c_discount.add(cartOrderProduct.getDiscount());

					crit.addEq("productId", formatToString(cartOrderProduct.getProdId()));
					crit.addEq("type", "MAIN");
					crit.addEq("isDelete", "N");
					List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
					int b1 = 0;
					for (Image img : images) {
						if (img.getImgFilePath().indexOf("_m135") != -1) {
							x_shoppingcart.addElement("image_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
							b1 = 1;
							break;
						}
					}
					if (b1 == 0) {
						x_shoppingcart.addElement("image_path").addText("");
					}

					List<CartOrderProductDetail> details = cartOrderProduct.getDetails();
					for (CartOrderProductDetail prodDetail : details) {
						if (prodDetail.getDetailTp().equals("2")) {
							Element x_gift = x_shoppingcart.addElement("gift");
							x_gift.addElement("gift_product_id").setText(prodDetail.getProdId());
							x_gift.addElement("gift_product_name").setText(prodDetail.getProdName());
						}
					}

					if ("6".equals(cartOrderProduct.getProdTp())) { // n-m
						for (CartOrderProductDetail prodDetail : details) {
							Element x_npickm = x_shoppingcart.addElement("npickm");
							x_npickm.addElement("npickm_product_id").setText(prodDetail.getProdId());
							x_npickm.addElement("npickm_product_name").setText(prodDetail.getProdName());
							x_npickm.addElement("npickm_specification_id").setText(prodDetail.getProdSpecId());
							x_npickm.addElement("npickm_specification_name").setText(prodDetail.getProdSpecName());
							x_npickm.addElement("npickm_product_image").setText(
									ServerValue.getImgDomain() + "/PImg/" + prodDetail.getProdId().substring(0, 4) + "/"
											+ prodDetail.getProdId() + "/" + prodDetail.getProdId() + "_m75.jpg");
						}
					}
				}

				for (CartOrderProduct cartOrderProduct : overbuyList) {
					Element x_overbuy = x_dataset.addElement("overbuy");
					x_overbuy.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_overbuy.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					Shelf shelf = shelfService.getShelfByProductId(cartOrderProduct.getProdId(), DateUtil.getCurrentTime(),
							DateUtil.getCurrentTime());
					x_overbuy.addElement("shelf_price").setText(formatToString(shelf.getShelfPrice()));
					x_overbuy.addElement("overbuy_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_overbuy.addElement("specification_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_overbuy.addElement("specification_name").setText(formatToString(cartOrderProduct.getProdSpecName()));

					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總加購商品金額

				}

				// ------------ 產生符合COD模式的Address
				String cartId = memberId;
				// UserData userData = new UserData(request, response);
				// String memberId = userData.getMemberId();
				if (memberId == null) {
					throw new YekMobileException("使用者尚未登入");
				}

				cartId = cartId + "_yekmobile";
				if (false == deliveryRuleService.chkProdDetailCanUseCod("cart", cartId)) {
					throw new YekMobileException("此购物车商品不能使用货到付款");
				}

				List<AddressBook> abList = null;
				if (StringUtils.isBlank(cartId)) {
					// abList = memberService.getAddressBookList(memberId);
				} else {
					Map<String, String> drMap = deliveryRuleService.findDeliveryType("cart", cartId);
					String deliveryType = drMap.get("deliveryType");
					if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
						abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType,
								drMap.get("fromProvince"), drMap.get("fromCity"), drMap.get("fromDistrict"));
					} else {
						// 大材积
						Map<String, String> prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(cartId);
						if (prodVolumeMap.size() > 0) {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "", true);
						} else {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "");
						}
					}
				}
				// for (int i = 0; i < abList.size(); i++) {
				// AddressBook ab = abList.get(i);
				AddressBook ab = null;
				if (abList.size() > 0) {
					ab = abList.get(0);
					// COD﹣收取手續費
					codFee = addressService.getCodFee();
					// 運費
					www = addressService.getFreight(ab.getProvince(), cartOrders.getWeightSum().multiply(new BigDecimal("1000")),
							cartOrders.getAmount().add(cartOrders.getDiscount()), cartOrders.getDiscount());
					Element x_addressinfo = x_dataset.addElement("addressinfo");
					x_addressinfo.addElement("addressid").setText(ab.getId().toString());
					x_addressinfo.addElement("receiver").setText(ab.getContactName());
					x_addressinfo.addElement("province").setText(ab.getProvince());
					x_addressinfo.addElement("city").setText(ab.getCity());
					x_addressinfo.addElement("district").setText(ab.getDistrict());
					x_addressinfo.addElement("address").setText(ab.getAddr());
					x_addressinfo.addElement("zip").setText(ab.getZipCode());
					if (StringUtils.isBlank(ab.getAreaCode())) {
						x_addressinfo.addElement("telarea").setText("");
					} else {
						x_addressinfo.addElement("telarea").setText(ab.getAreaCode());
					}
					if (StringUtils.isBlank(ab.getPhone())) {
						x_addressinfo.addElement("tel").setText("");
					} else {
						x_addressinfo.addElement("tel").setText(ab.getPhone());
					}
					if (StringUtils.isBlank(ab.getMobile())) {
						x_addressinfo.addElement("mobileno").setText("");
					} else {
						x_addressinfo.addElement("mobileno").setText(ab.getMobile());
					}
					// if (i == 0)
					x_addressinfo.addElement("default").setText("Y");
					// else
					// x_addressinfo.addElement("default").setText("N");
					// }
				} else {
					document = DocumentHelper.createDocument();
					x_dataset = document.addElement("dataset");
					this.createSuccessResult(document, "无地址项目");
					return "finish";
				}
				// --------------------------------------
				String paytype = "cash";
				DeliveryRule dr = null;
				if (paytype.equals("pos")) {
					dr = deliveryRuleService.getCartDeliveryRule(cartId, ab.getProvince(), ab.getCity(), ab.getDistrict(), "30");
				} else {
					dr = deliveryRuleService.getCartDeliveryRule(cartId, ab.getProvince(), ab.getCity(), ab.getDistrict(), "20");
				}
				if (null == dr) {
					throw new YekMobileException("此地址不符合货到付款地址");
				}
				// ----------------产生加总XML讯息
				Element x_paytype = x_dataset.addElement("paytype");
				if (paytype.equals("pos")) {
					x_paytype.addElement("itemtype2").setText("货到付款-POS机");
				} else {
					x_paytype.addElement("itemtype1").setText("货到付款-现金");
				}
				Element x_summary = x_dataset.addElement("summary");
				x_summary.addElement("subtotal").setText(formatToString(c_total)); // 商品小计
				x_summary.addElement("carriage").setText(formatToString(www)); // 运费
				x_summary.addElement("poundage").setText(formatToString(codFee)); // 货到付款
				x_summary.addElement("cheapdiscount").setText(formatToString(c_discount)); // 折扣礼卷
				x_summary.addElement("cheapcoupon").setText("0.0"); // 折扣购物金
				x_summary.addElement("accountpay").setText("0.0"); // 账户余额支付
				x_summary.addElement("totalsum").setText(formatToString(c_total.subtract(c_discount).add(www).add(codFee))); // 你总共需要支付
				// --------------------------------------
			}

			this.createSuccessResult(document);
			cartOrdersService.delete(cartOrders);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误");
		}

		return "finish";
	}

	/**
	 * 44. 增加修改立即購買结算中心接口
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkdirect() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		List<CartOrderProduct> cartOrderProductList = null;

		BigDecimal c_total = BigDecimal.valueOf(0.0);
		BigDecimal c_discount = BigDecimal.valueOf(0.0);

		BigDecimal codFee = BigDecimal.valueOf(0.0);
		BigDecimal www = BigDecimal.valueOf(0.0);
		// 驗證weblogid
		if (!this.isSessionValid(request)) {
			this.createErrorResult(MESSAGE_SESSION_INVALID);
			return "finish";
		}

		try {
			UserData userData = new UserData(request, response);
			if (StringUtils.isBlank(userData.getLoginId())) {
				throw new YekMobileException("无登入讯息");
			}

			String memberId = userData.getMemberId();
			// CartOrders cartOrders = cartOrdersService.getCart(memberId, memberId + "_yekmobile");
			// if (memberId.equals(cartOrders.getCartId())) {
			// cartOrders = cartOrdersService.createCart(memberId + "_yekmobile", null, null, null, 0, null, null);
			// }
			CartOrders cartOrders = createBuyNowCart(request, userData);
			// 產生XML
			Document document = DocumentHelper.createDocument();
			Element x_dataset = document.addElement("dataset");

			if (cartOrders != null) {
				Map<String, String> optional = new HashMap<String, String>();
				optional.put("domain", request.getServerName());
				optional.put("cookie", userData.getApplySource());
				cartOrders = cartOrdersService.calculateCart(cartOrders, optional); // 每次從新計算shopping cart的金額

				cartOrderProductList = cartOrders.getCartOrderProducts();
				CommonCriteria crit = new CommonCriteria();

				List<CartOrderProduct> overbuyList = new ArrayList<CartOrderProduct>();
				for (CartOrderProduct cartOrderProduct : cartOrderProductList) {
					if (cartOrderProduct.getProdTp().equals("5")) {
						overbuyList.add(cartOrderProduct);
						continue;
					}
					List<String> tlpList = timeLimitSaleService.findTimeLimitSale(cartOrders.getCartOrderProducts());

					Element x_shoppingcart = x_dataset.addElement("shoppingdirect");
					x_shoppingcart.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_shoppingcart.addElement("cart_order_product_id").setText(
							formatToString(cartOrderProduct.getCartOrderProdId()));
					x_shoppingcart.addElement("campaign_id").setText(formatToString(cartOrderProduct.getCampaignId()));
					x_shoppingcart.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					x_shoppingcart.addElement("campaign_name").setText(formatToString(cartOrderProduct.getCampaignName()));
					x_shoppingcart.addElement("category_Path").setText(formatToString(cartOrderProduct.getCategoryPath()));
					int c = 0;
					if (tlpList != null) {
						for (int b = 0; b < tlpList.size(); b++) {
							if (tlpList.get(b).equals(cartOrderProduct.getProdId())) {
								x_shoppingcart.addElement("promote_name").setText("timelimitsales");
								c = 1;
							}
						}
					}
					if (c == 0) {
						x_shoppingcart.addElement("promote_name").setText("");
					}
					x_shoppingcart.addElement("product_spec_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_shoppingcart.addElement("product_spec_name").setText(formatToString(cartOrderProduct.getProdSpecName()));
					x_shoppingcart.addElement("product_Tp").setText(formatToString(cartOrderProduct.getProdTp()));

					x_shoppingcart.addElement("discount").setText(String.valueOf(cartOrderProduct.getDiscount()));
					x_shoppingcart.addElement("qty").addText(String.valueOf(cartOrderProduct.getQty()));
					x_shoppingcart.addElement("unit_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_shoppingcart.addElement("total_price").setText(formatToString(cartOrderProduct.getTotalPrice()));
					Product product = product2Service.get(cartOrderProduct.getProdId());
					if ((product.getProductType() != 6 && "N".equals(product.getCanUseCod())) || "Y".equals(product.getIsScm())) {
						x_shoppingcart.addElement("canusecod").setText("N");
					} else {
						x_shoppingcart.addElement("canusecod").setText("Y");
					}
					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總購物車商品金額
					c_discount = c_discount.add(cartOrderProduct.getDiscount());

					crit.addEq("productId", formatToString(cartOrderProduct.getProdId()));
					crit.addEq("type", "MAIN");
					crit.addEq("isDelete", "N");
					List<Image> images = imageservice.getList(1, 10, crit, new String[] { "id desc" });
					int b1 = 0;
					for (Image img : images) {
						if (img.getImgFilePath().indexOf("_m135") != -1) {
							x_shoppingcart.addElement("image_path").addText(ServerValue.getImgDomain() + img.getImgFilePath());
							b1 = 1;
							break;
						}
					}
					if (b1 == 0) {
						x_shoppingcart.addElement("image_path").addText("");
					}

					List<CartOrderProductDetail> details = cartOrderProduct.getDetails();
					for (CartOrderProductDetail prodDetail : details) {
						if (prodDetail.getDetailTp().equals("2")) {
							Element x_gift = x_shoppingcart.addElement("gift");
							x_gift.addElement("gift_product_id").setText(prodDetail.getProdId());
							x_gift.addElement("gift_product_name").setText(prodDetail.getProdName());
						}
					}

					if ("6".equals(cartOrderProduct.getProdTp())) { // n-m
						for (CartOrderProductDetail prodDetail : details) {
							Element x_npickm = x_shoppingcart.addElement("npickm");
							x_npickm.addElement("npickm_product_id").setText(prodDetail.getProdId());
							x_npickm.addElement("npickm_product_name").setText(prodDetail.getProdName());
							x_npickm.addElement("npickm_specification_id").setText(prodDetail.getProdSpecId());
							x_npickm.addElement("npickm_specification_name").setText(prodDetail.getProdSpecName());
							x_npickm.addElement("npickm_product_image").setText(
									ServerValue.getImgDomain() + "/PImg/" + prodDetail.getProdId().substring(0, 4) + "/"
											+ prodDetail.getProdId() + "/" + prodDetail.getProdId() + "_m75.jpg");
						}
					}
				}

				for (CartOrderProduct cartOrderProduct : overbuyList) {
					Element x_overbuy = x_dataset.addElement("overbuy");
					x_overbuy.addElement("product_id").setText(formatToString(cartOrderProduct.getProdId()));
					x_overbuy.addElement("product_name").setText(formatToString(cartOrderProduct.getProdName()));
					Shelf shelf = shelfService.getShelfByProductId(cartOrderProduct.getProdId(), DateUtil.getCurrentTime(),
							DateUtil.getCurrentTime());
					x_overbuy.addElement("shelf_price").setText(formatToString(shelf.getShelfPrice()));
					x_overbuy.addElement("overbuy_price").setText(formatToString(cartOrderProduct.getUnitPrice()));
					x_overbuy.addElement("specification_id").setText(formatToString(cartOrderProduct.getProdSpecId()));
					x_overbuy.addElement("specification_name").setText(formatToString(cartOrderProduct.getProdSpecName()));

					c_total = c_total.add(cartOrderProduct.getUnitPrice().multiply(new BigDecimal(cartOrderProduct.getQty()))); // 加總加購商品金額

				}

				// ------------ 產生符合COD模式的Address
				String cartId = memberId;
				if (StringUtils.isBlank(cartId)) {
					throw new YekMobileException("cartId未输入");
				}
				cartId = cartId + "_yekmobile";
				// UserData userData = new UserData(request, response);
				// String memberId = userData.getMemberId();
				if (memberId == null) {
					throw new YekMobileException("使用者尚未登入");
				}
				if (false == deliveryRuleService.chkProdDetailCanUseCod("cart", cartId)) {
					throw new YekMobileException("此购物车商品不能使用货到付款");
				}
				List<AddressBook> abList = null;
				if (StringUtils.isBlank(cartId)) {
					// abList = memberService.getAddressBookList(memberId);
				} else {
					Map<String, String> drMap = deliveryRuleService.findDeliveryType("cart", cartId);
					String deliveryType = drMap.get("deliveryType");
					if (StringUtils.equalsIgnoreCase(ServerValue.getScmType(), deliveryType)) {
						abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType,
								drMap.get("fromProvince"), drMap.get("fromCity"), drMap.get("fromDistrict"));
					} else {
						// 大材积
						Map<String, String> prodVolumeMap = cartordersService.chkVolumeOfCartOrderDetail(cartId);
						if (prodVolumeMap.size() > 0) {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "", true);
						} else {
							abList = memberService.getCanUseAddressBook(userData.getMemberId(), deliveryType, "", "", "");

						}
					}
				}

				String addressed = StringUtils.defaultString(request.getParameter("addressed"));
				if (StringUtils.isBlank(addressed)) {
					throw new YekMobileException("addressed未输入");
				}
				AddressBook inputAddressBook = null;// 输入的地址簿
				AddressBook ab = null;// 最终可用的地址簿
				if (StringUtils.isNotBlank(addressed)) {
					inputAddressBook = memberService.getAddressBook(Long.parseLong(addressed));
				}
				if (null == inputAddressBook) {
					document = DocumentHelper.createDocument();
					x_dataset = document.addElement("dataset");
					this.createSuccessResult(document, "无地址项目");
					return "finish";
				}
				String paytype = StringUtils.defaultString(request.getParameter("paytype"));
				DeliveryRule dr = null;

				if (paytype.equals("cash")) {
					dr = deliveryRuleService.getCartDeliveryRule(memberId, inputAddressBook.getProvince(),
							inputAddressBook.getCity(), inputAddressBook.getDistrict(), "20");
				}
				if (paytype.equals("pos")) {
					dr = deliveryRuleService.getCartDeliveryRule(memberId, inputAddressBook.getProvince(),
							inputAddressBook.getCity(), inputAddressBook.getDistrict(), "30");
				}
				if (null == dr) {
					throw new YekMobileException("此地址不符合货到付款地址");
				}

				ab = inputAddressBook;
				if (null != ab) {

					// COD﹣收取手續費
					codFee = addressService.getCodFee();
					// 運費
					www = addressService.getFreight(ab.getProvince(), cartOrders.getWeightSum().multiply(new BigDecimal("1000")),
							cartOrders.getAmount().add(cartOrders.getDiscount()), cartOrders.getDiscount());
					Element x_addressinfo = x_dataset.addElement("addressinfo");
					x_addressinfo.addElement("addressid").setText(ab.getId().toString());
					x_addressinfo.addElement("receiver").setText(ab.getContactName());
					x_addressinfo.addElement("province").setText(ab.getProvince());
					x_addressinfo.addElement("city").setText(ab.getCity());
					x_addressinfo.addElement("district").setText(ab.getDistrict());
					x_addressinfo.addElement("address").setText(ab.getAddr());
					x_addressinfo.addElement("zip").setText(ab.getZipCode());
					if (StringUtils.isBlank(ab.getAreaCode())) {
						x_addressinfo.addElement("telarea").setText("");
					} else {
						x_addressinfo.addElement("telarea").setText(ab.getAreaCode());
					}
					if (StringUtils.isBlank(ab.getPhone())) {
						x_addressinfo.addElement("tel").setText("");
					} else {
						x_addressinfo.addElement("tel").setText(ab.getPhone());
					}
					if (StringUtils.isBlank(ab.getMobile())) {
						x_addressinfo.addElement("mobileno").setText("");
					} else {
						x_addressinfo.addElement("mobileno").setText(ab.getMobile());
					}
					// if (i == 0)
					// x_addressinfo.addElement("default").setText("Y");
					// else
					// x_addressinfo.addElement("default").setText("N");
				}

				// ----------------产生加总XML讯息
				Element x_paytype = x_dataset.addElement("paytype");

				if (paytype.equals("cash")) {
					x_paytype.addElement("itemtype").setText("货到付款-现金");
				}
				if (paytype.equals("pos")) {
					x_paytype.addElement("itemtype").setText("货到付款-POS机");
				}
				Element x_summary = x_dataset.addElement("summary");
				x_summary.addElement("subtotal").setText(formatToString(c_total)); // 商品小计
				x_summary.addElement("carriage").setText(formatToString(www)); // 运费
				x_summary.addElement("poundage").setText(formatToString(codFee)); // 货到付款
				x_summary.addElement("cheapdiscount").setText(formatToString(c_discount)); // 折扣礼卷
				x_summary.addElement("cheapcoupon").setText("0.0"); // 折扣购物金
				x_summary.addElement("accountpay").setText("0.0"); // 账户余额支付
				x_summary.addElement("totalsum").setText(formatToString(c_total.subtract(c_discount).add(www).add(codFee))); // 你总共需要支付
				// --------------------------------------
			}

			this.createSuccessResult(document);
			cartOrdersService.delete(cartOrders);
		} catch (YekMobileException e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("YekMobileAction.golistCart error :{}", e.toString());
			this.createErrorResult("获取失败", "获取数据有误");
		}

		return "finish";
	}

	@Override
	public void prepare() throws Exception {
		super.prepare();

		if (paymentTpMenu == null) {
			paymentTpMenu = menuService.get("Order.PaymentTp");
		}

		if (orderStMenu == null) {
			orderStMenu = menuService.get("Order.status");
		}

		if (null == systemValueMenu) {
			systemValueMenu = menuService.get("SystemValue");
		}

	}

	private CartOrders processMoveTmpCartToCartOrder(String tmpCartid, String memberCartId,
			CartOrdersService cartordersService, UserData userData) throws Exception {
		// 若memberCartId為空，則新增一個cartOrders
		// logger.info("memberCartId:{}", memberCartId);
		CartOrders cartOrders = null;

		if (memberCartId == null) {
			cartOrders = cartordersService.createCart(userData.getMemberId() + "_yekmobile", null, null, null, 0, null, null);
			memberCartId = cartOrders.getCartId();
			userData.writeRawValue("cartid", cartOrders.getCartId());
			// memberCartId = createNewCartOrders(memberCartId, userData);
		} else {
			// cartOrders = cartordersService.getCart(null, memberCartId);
		}
		// logger.info("cartOrders:{}", cartOrders);
		if (StringUtils.isNotBlank(tmpCartid)) {
			CartOrders tmpCart = cartordersService.get(tmpCartid + "_yekmobile");
			if (null != tmpCart) {
				boolean hasTempQP = false;
				// 检查暂存购物车内是否有满额购，若有，移除会员购物车内之满额购
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {
					if (cop.getProdTp().equals(Product.PRODUCT_TYPE.QUOTAFILLED.getValue())) {
						// 若有满额购
						hasTempQP = true;
					}
				}
				if (hasTempQP) {
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (memberCop.getProdTp().equals(Product.PRODUCT_TYPE.QUOTAFILLED.getValue())) {
							cartOrders.getCartOrderProducts().remove(memberCop);
							break;
						}
					}
				}

				// 將暫存的車移至cartOrderProduct
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {

					boolean isItemExists = false;
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (cop.getProdId().equals(memberCop.getProdId()) && cop.getProdSpecId().equals(memberCop.getProdSpecId())) {
							isItemExists = true;
							break;
						}
					}
					if (!isItemExists) {
						CartOrderProduct tmpcop = new CartOrderProduct();
						// tmpcop.setAmount(new BigDecimal(0.00));
						BeanUtils.copyProperties(cop, tmpcop, new String[] { "cartOrderProdId", "cartOrder", "coupon",
								"modifyDate", "details" });
						// logger.info("tmpcop:{}", tmpcop.getAmount());
						cartOrders.addCartOrderProduct(tmpcop);
						for (CartOrderProductDetail detail : cop.getDetails()) {
							CartOrderProductDetail cloneDetail = new CartOrderProductDetail();
							BeanUtils.copyProperties(detail, cloneDetail, new String[] { "cartOrderDetailId", "cartOrderProdId",
									"orderProduct", "cartId", "cartOrder", "modifyDate", "details" });
							tmpcop.addDetail(cloneDetail);

						}
					}
				}
				// 刪除暫存車的cartOrders
				cartOrders = cartordersService.save(cartOrders);
				cartordersService.delete(tmpCart);
			}
		}
		return cartOrders;
	}

	private String[] getProductSpecStr(List<Specification> specList) throws Exception {
		StringBuffer id = new StringBuffer();
		StringBuffer name = new StringBuffer();
		StringBuffer inv = new StringBuffer();
		for (Specification spec : specList) {
			if ("Y".equals(spec.getIsDelete())) {
				continue;
			}
			String hql = "from SpecificationInventory where specId=?";
			SpecificationInventory si = (SpecificationInventory) baseMgr.queryByHql(hql,
					new Object[] { spec.getSpecificationId() }, 0, 1)[0];
			Integer inventory = si.getInventory();

			id.append(spec.getSpecificationId()).append(",");
			name.append(spec.getSpecificationName()).append(",");
			inv.append(inventory).append(",");
		}
		if (id.length() > 0) {
			id.deleteCharAt(id.length() - 1);
			name.deleteCharAt(name.length() - 1);
			inv.deleteCharAt(inv.length() - 1);
		}
		return new String[] { id.toString(), name.toString(), inv.toString() };
	}

	private String updateCartDetail(CartOrderProduct cop, CartOrderProduct copCurrent) {
		String cartMessage = "";
		String hql = "from SpecificationInventory where specId=?";

		for (CartOrderProductDetail copd : cop.getDetails()) {
			// 调整主商品spec
			if (copd.getProdSpecId().equals(copCurrent.getProdSpecId())) {
				copd.setProdSpecId(cop.getProdSpecId());
				copd.setProdSpecName(cop.getProdSpecName());
				copd.setQty(cop.getQty());
			} else

			// 調整加購商品數量
			if (copd.getDetailTp().equals(Product.PRODUCT_TYPE.ADDON.getValue())) {
				// 檢查庫存

				SpecificationInventory siad = (SpecificationInventory) baseMgr.queryByHql(hql,
						new Object[] { copd.getProdSpecId() }, 0, 1)[0];
				Integer inventoryad = siad.getInventory();
				if (copd.getQty() > cop.getQty()) {
					copd.setQty(cop.getQty());
				}
				if (copd.getQty() > inventoryad) {
					cartMessage += " 调整加购商品数量";
					copd.setQty(inventoryad);
				}
				/*
				 * // do something if (inventoryad <= 0) { // 庫存不足 cartMessage += "加购商品库存不足无法购买！"; copd.setQty(0);
				 * 
				 * } else { // 调整加购商品数量 if (copd.getQty() > inventoryad && cop.getQty() > inventoryad) { cartMessage +=
				 * " 调整加购商品数量"; copd.setQty(inventoryad); } else if (copd.getQty() > cop.getQty() && inventoryad >
				 * copd.getQty()) { copd.setQty(cop.getQty()); } else { // ?? } }
				 */
				break;
			} else
			// 赠品
			if (copd.getDetailTp().equals(Product.PRODUCT_TYPE.PRESENT.getValue())) {
				// 檢查庫存
				SpecificationInventory sips = (SpecificationInventory) baseMgr.queryByHql(hql,
						new Object[] { copd.getProdSpecId() }, 0, 1)[0];
				Integer inventoryps = sips.getInventory();
				copd.setQty(cop.getQty());
				if (copd.getQty() > inventoryps) {
					cartMessage += " 赠品库存不足，已调整为：" + inventoryps;
					copd.setQty(inventoryps);
				}
				/*
				 * if (inventoryps <= 0) { cartMessage += " 赠品库存不足！"; copd.setQty(0); } else {
				 * 
				 * // 調整贈品數量 if (inventoryps > cop.getQty()) { copd.setQty(cop.getQty()); } else { cartMessage +=
				 * " 赠品库存不足，已调整为：" + inventoryps; copd.setQty(inventoryps); } }
				 */
			}
			baseMgr.update(copd);
		}

		// baseMgr.update(cop);
		return cartMessage;
	}

	private void generateXMLResult(Document document) throws Exception {
		StringWriter out = new StringWriter();
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(out, format);

		writer.write(document);
		writer.flush();
		writer.close();

		this.setXML_Result(out.toString());
	}

	private void createSuccessResult(Document document) throws Exception {
		this.createSuccessResult(document, null);
	}

	private void createSuccessResult(Document document, String desc) throws Exception {
		Element x_dataset = document.getRootElement();
		Element x_queryresult = x_dataset.addElement("queryresult");
		x_queryresult.addElement("result").setText("true");
		x_queryresult.addElement("title").setText("成功");
		if (desc == null) {
			x_queryresult.addElement("desc").setText("");
		} else {
			x_queryresult.addElement("desc").setText(desc);
		}

		this.generateXMLResult(document);
	}

	private void createErrorResult(String desc) throws Exception {
		this.createErrorResult(null, desc);
	}

	private void createErrorResult(String title, String desc) throws Exception {
		Document document = DocumentHelper.createDocument();

		Element x_dataset = document.addElement("dataset");
		Element x_queryresult = x_dataset.addElement("queryresult");
		x_queryresult.addElement("result").setText("false");
		if (title != null) {
			x_queryresult.addElement("title").setText(title);
		} else {
			x_queryresult.addElement("title").setText("失败");
		}
		x_queryresult.addElement("desc").setText(desc);
		this.generateXMLResult(document);
	}

	private void createErrorResult(String title, String desc, String exception) throws Exception {
		Document document = DocumentHelper.createDocument();

		Element x_dataset = document.addElement("dataset");
		Element x_queryresult = x_dataset.addElement("queryresult");
		x_queryresult.addElement("result").setText("false");
		if (title != null) {
			x_queryresult.addElement("title").setText(title);
		} else {
			x_queryresult.addElement("title").setText("失败");
		}
		x_queryresult.addElement("desc").setText(desc);
		if (exception != null) {
			x_queryresult.addElement("exception").addComment(exception);
		}
		this.generateXMLResult(document);
	}

	private boolean isSessionValid(HttpServletRequest request) {
		if ("Y".equals(request.getParameter("debug"))) {
			return true;
		}
		String weblogid = request.getParameter("weblogid");
		// String sWeblogid = (String) request.getSession().getAttribute("WEBLOGID");
		String sWeblogid = getCookieValue("WEBLOGID");
		logger.info("YekMobileAction.isSessionValid weblogid :{}", weblogid);
		logger.info("YekMobileAction.isSessionValid sWeblogid :{}", sWeblogid);
		try {
			return weblogid.equals(sWeblogid);
		} catch (Exception e) {
			return false;
		}
	}

	private String formatToString(Object obj) {
		if (obj == null) {
			return "";
		}
		return obj.toString().trim();
	}

	private String formatTimeToString(Date date) {
		if (date == null) {
			return "";
		}
		return timeFormat.format(date);
	}

	public String getXML_Result() {
		return XML_Result;
	}

	public void setXML_Result(String xML_Result) {
		XML_Result = xML_Result;
	}

	private String getCookieValue(String name) {
		return getValue(name, false);
	}

	private String getDecodedCookieValue(String name) {
		return getValue(name, true);
	}

	private String getValue(String name, boolean decode) {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);

		Cookie[] cookies = request.getCookies();
		if (cookies == null) {
			return null;
		}
		for (int i = 0; i < cookies.length; i++) {
			Cookie c = cookies[i];
			if (name.equals(c.getName())) {
				String value = c.getValue();
				if (decode) {
					return value == null ? "" : PasswordUtils.decodePassword(value, null); // 要decode
				} else {
					return value == null ? "" : value;
				}
			}
		}
		return null; // not found
	}

	private void setValue(String name, String value, boolean decode) {
		if (name == null) {
			return;
		}
		if (value == null) {
			clear(name);
		} else {
			if (decode) {
				add(name, PasswordUtils.encodePassword(value, null)); // 需要encode
			} else {
				add(name, value);
			}
		}
	}

	private void clear(String name) {
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		Cookie c = new Cookie(name, null);
		c.setMaxAge(0); // A zero value causes the cookie to be deleted.
		response.addCookie(c);
	}

	private void add(String name, String value) {
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);

		Cookie c = new Cookie(name, value);

		response.addCookie(c);
	}

	class YekMobileException extends Exception {
		public YekMobileException() {
			super();
		}

		public YekMobileException(String message) {
			super(message);
		}

		public YekMobileException(String message, Throwable cause) {
			super(message, cause);
		}

		public YekMobileException(Throwable cause) {
			super(cause);
		}
	}

}
